一、前言
最近一直忙着参与公司的新项目开发,由于临期上线,正在对系统进行性能压测,在这个过程中,发现一些代码有性能优化的空间。因此决定写一篇文章,把本次以及今后,遇到的性能优化的 case 都记录下来,希望对大家们的编码水平能够有所帮助。
源码链接:https://github.com/jitwxs/blog-sample/blob/master/Java/performance_optimized
二、Java 基础
2.1 字符串拼接
在我们的系统中,存在着大量的缓存,这些缓存的 key 值根据请求参数的不同而拼接起来,如下代码所示:
public class LastPriceCache {
private String keySuffix = "last_price_%s";
public double getLastPrice(int id) {
return redisService.get(this.generatorKey(id));
}
private String generatorKey(int id) {
return String.format(keySuffix, id);
}
}
字符串拼接存在性能损耗,如果 id 值是可预期的,完全可以将其在内存中缓存起来,如下代码所示:
public class LastPriceCache {
private String keySuffix = "last_price_%s";
private Map<Integer, String> keyMap = new HashMap<>();
public double getLastPrice(int id) {
return redisService.get(this.generatorKey(id));
}
private String generatorKey(int id) {
String result;
if(!keyMap.containsKey(id))

最低0.47元/天 解锁文章
429

被折叠的 条评论
为什么被折叠?



