背景介绍
当我们在纠结哪种写法性能更好时,不如找一个靠谱的工具来协助测量一下真实耗时
在这里介绍一下 Spring 框架内 util 包下自带的 StopWatch 工具类:
- 所在包:
org.springframework.util.StopWatch - 启动:
start() - 停止:
stop() - 总耗时(毫秒):
getTotalTimeMillis()
注意:对于一个 StopWatch 对象,stop 后再 start 时间会继续计时,而非重新计时
代码样例
public static void main(String[] args) {int[] array = new int[]{1, 2, 3, 4, 5};StopWatch sw1 = new StopWatch();sw1.start();for (int i = 0; i < 1000000; i++) {Arrays.stream(array).sum();}sw1.stop();System.out.println("Arrays.stream :" + sw1.getTotalTimeMillis());StopWatch sw2 = new StopWatch();sw2.start();for (int i = 0; i < 1000000; i++) {IntStream.of(array).sum();}sw2.stop();System.out.println("IntStream :" + sw2.getTotalTimeMillis());}
