在老外的两篇博文中,https://plumbr.io/blog/performance-blog/more-about-spring-cache-performance ,https://plumbr.io/blog/performance-blog/spring-cache-profiling
分别讲解了,在@cache注解中,使用参数速度变慢(通过JMH)基准测试工具测试。
不使用参数:
@Cacheable("time")
public long annotationBased(String dummy) {
return System.currentTimeMillis();
}
public long manual(String dummy) {
Cache.ValueWrapper valueWrapper = cache.get(dummy);
long result;
if (valueWrapper == null) {
result = System.currentTimeMillis();
cache.put(dummy, result);
} else {
result = (long) valueWrapper.get();
}
return result;
}
JMH结果:
Benchmark Mode Cnt Score Error Units
CacheBenchmark.annotationBased avgt 5 245.960 ± 27.749 ns/op
CacheBenchmark.manual avgt 5 16.696 ± 0.496 ns/op
CacheBenchmark.nocache avgt 5 44.586 ± 9.091 ns/op
可以看到,avgt是平均执行每次操作的耗费时间长短,手工的快;
再看注解中有参数的:
@Cacheable(value = "time", key = "#p0.concat(#p1)")
public long annotationWithSpel(String dummy1, String dummy2) {
return System.currentTimeMillis();
}
@Cacheable(value = "time")
public long annotationBased(String dummy1, String dummy2) {
return System.currentTimeMillis();
}
JMH测试结果:
Benchmark Mode Cnt Score Error Units标签:String,变慢,spring,cache,long,result,avgt,ns From: https://blog.51cto.com/u_14230175/5928136
CacheBenchmark.annotationBased avgt 5 271.975 ± 11.586 ns/op
CacheBenchmark.spel avgt 5 1196.744 ± 93.765 ns/op
CacheBenchmark.manual avgt 5 16.325 ± 0.856 ns/op
CacheBenchmark.nocache avgt 5 40.142 ± 4.012 ns/op