今天闲的无聊简单测试了下jdk Lambda表达式运行效率,取50000个随机数分别【循环每个值加1】、【排序】、【Stream取偶数】三种处理进行Lambda与java常规写法进行比较耗时;
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 50000; i++){
list.add((int)(Math.random() * 1000000));
}
- 循环
public static void testForEach1(List<Integer> list){ long begin = System.currentTimeMillis(); list.forEach(i -> {i = i + 1;}); long end = System.currentTimeMillis(); System.out.println("测试【Lambda】-> forEach耗时:" + ((end - begin) / 1000.0) + "秒"); }
public static void testForEach2(List<Integer> list){ long begin = System.currentTimeMillis(); for(Integer i : list){ i = i + 1; } long end = System.currentTimeMillis(); System.out.println("测试【非Lambda】-> forEach耗时:" + ((end - begin) / 1000.0) + "秒"); }
- 运行结果:
测试【Lambda】-> forEach耗时:0.04秒 测试【非Lambda】-> forEach耗时:0.002秒
可见常规写法比lambda快10倍多
- 排序
public static void testSort1(List<Integer> list){ long begin = System.currentTimeMillis(); Collections.sort(list, (a, b) -> {return a - b;}); long end = System.currentTimeMillis(); System.out.println("测试【Lambda】-> sort耗时:" + ((end - begin) / 1000.0) + "秒"); }
public static void testSort2(List<Integer> list){ long begin = System.currentTimeMillis(); Collections.sort(list, new Comparator<Integer>(){ @Override public int compare(Integer a, Integer b) { return a - b; } }); long end = System.currentTimeMillis(); System.out.println("测试【非Lambda】-> sort耗时:" + ((end - begin) / 1000.0) + "秒"); }
- 运行结果:
测试【Lambda】-> sort耗时:0.043秒 测试【非Lambda】-> sort耗时:0.017秒
都是运行简单的排序运行,常规写法依旧比Lambda快
- Stream取偶数
public static void testStream1(List<Integer> list){ long begin = System.currentTimeMillis(); list.stream().filter((i) -> (i % 2 == 0)); long end = System.currentTimeMillis(); System.out.println("测试【Lambda】-> Stream取偶数耗时:" + ((end - begin) / 1000.0) + "秒"); }
public static void testStream2(List<Integer> list){ long begin = System.currentTimeMillis(); list.stream().filter(new Predicate<Integer>(){ @Override public boolean test(Integer i) { return i % 2 == 0; } }); long end = System.currentTimeMillis(); System.out.println("测试【非Lambda】-> Stream取偶数耗时:" + ((end - begin) / 1000.0) + "秒"); }
- 运行结果:
测试【Lambda】-> Stream取偶数耗时:0.029秒 测试【非Lambda】-> Stream取偶数耗时:0.001秒
只是简单的测试几种方式,如有错望纠正;Lambda表达式确实优雅了很多,但是效率上确实没有常规写法快,另外说明一下beak与continue只能在循环里面使用;希望后续版本能优化性能及提供更多优雅的写法