王牌竞速鸿蒙版
1.94G · 2025-10-21
public class PerformanceOptimizationDemo {
private static final Method METHOD;
static {
METHOD = "获取method";
}
}
更多细节见 Java反射性能详解
public static int getRandomNum() {
// 性能略差
return new Random().nextInt();
// 性能更好的平替
return ThreadLocalRandom.current().nextInt();
}
public class PerformanceOptimizationDemo {
private PerformanceOptimizationDemo(){
}
private static class LazyHolder {
private static final PerformanceOptimizationDemo INSTANCE = new PerformanceOptimizationDemo();
}
protected static PerformanceOptimizationDemo getInstance() {
return PerformanceOptimizationDemo.LazyHolder.INSTANCE;
}
}
private static final ObjectMapper DEFAULT_OBJECT_MAPPER = getObjectMapper();
@Override
@Cached(name = "user.", key = "#id", expire = 3600, cacheType = CacheType.REMOTE, postCondition = "result != null")
public UserInfo getData(Long id) {
return Optional.ofNullable(userMapper.selectById(id))
.map(user -> convert(user, UserInfo.class))
.orElse(null);
}
9.接上一条,业务配置数据在初始化时直接加载到缓存和内存,优先从内存和缓存读取,没有再去读数据库并加载到内存和缓存中 10. Mq消息批处理 11. 数据库批处理(尽量不要在for循环里面进行数据库操作),注意jdbc参数rewriteBatchedStatements和allowMultiQueries要为true
private final UserMapper userMapper;
public void batchInsert(List<UserDo> userList) {
// 此种操作会占用较多的数据库连接且多次访问数据库rt会慢很多
userList.forEach(user -> userMapper.insert(user));
}
@Transactional(readOnly = true)
public void doSomething() {
doQuery0();
doQuery1();
doQuery2();
}
public static void writeToFile(String filePath, String content) throws IOException {
try (FileOutputStream fos = new FileOutputStream(filePath);
FileChannel channel = fos.getChannel()) {
// 将内容转换为字节数组
byte[] bytes = content.getBytes();
// 创建ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
buffer.put(bytes);
// 将Buffer切换为读取模式
buffer.flip();
// 将数据写入到文件通道
while (buffer.hasRemaining()) {
channel.write(buffer);
}
}
}
性能优化没有银弹,所有的优化要以业务的诉求和业务量为基石,实践是检验真理的唯一标准。
原文地址: pebble-skateboard-d46.notion.site/Java-9e8e05…