学校教务网站的设计与实现,查看网页源代码,app开发公司部门,wordpress 登陆签到针对同一个集合#xff0c;用 stream 操作两次得到两个不同条件筛选出来的集合和map#xff0c;和一次for循环就搞定搞定的效率对比。虽然stream写起来链式操作很舒服#xff0c;但效率在不同数据量下的体现效果是不一样的#xff0c;以下为我的测试代码#xff1a;Testpu…针对同一个集合用 stream 操作两次得到两个不同条件筛选出来的集合和map和一次for循环就搞定搞定的效率对比。虽然stream写起来链式操作很舒服但效率在不同数据量下的体现效果是不一样的以下为我的测试代码Testpublic void testStreamAndFor() {List studentList new ArrayList();// 初始数据量int listSize 100000;// 测试次数以便求出平均运行时长int testTimes 5;for (int i 0; i listSize; i) {Student student new Student();student.setId(i 1);student.setStudentName(name i);student.setAge(i);studentList.add(student);}BigDecimal streamTotalRunTime new BigDecimal(0);BigDecimal forTotalRunTime new BigDecimal(0);for (int i 0; i testTimes; i) {Instant streamStart Instant.now();Map idMapOfStream studentList.stream().collect(Collectors.toMap(Student::getId, v - v));List studentAgeListOfStream studentList.stream().map(Student::getAge).collect(Collectors.toList());long streamRunTime Duration.between(streamStart, Instant.now()).toMillis();System.out.println(第 (i 1) 次 stream 耗时 streamRunTime);Instant forStart Instant.now();int size studentList.size();Map idMapOfFor new HashMap(size);List ageListOfFor new ArrayList();for (Student student : studentList) {idMapOfFor.put(student.getId(), student);ageListOfFor.add(student.getAge());}long forRunTime Duration.between(forStart, Instant.now()).toMillis();System.out.println(第 (i 1) 次 for 耗时 forRunTime);streamTotalRunTime streamTotalRunTime.add(new BigDecimal(streamRunTime ));forTotalRunTime forTotalRunTime.add(new BigDecimal(forRunTime ));}System.out.println(list长度为 listSize 总共测试次数 testTimes);System.out.println(stream总运行时间(ms) streamTotalRunTime);System.out.println(for总运行时间(ms) forTotalRunTime);BigDecimal streamAverageRunTime streamTotalRunTime.divide(new BigDecimal(testTimes ), 2, BigDecimal.ROUND_HALF_UP);System.out.println(stream平均每次运行时间(ms) streamAverageRunTime);BigDecimal forAverageRunTime forTotalRunTime.divide(new BigDecimal(testTimes ), 2, BigDecimal.ROUND_HALF_UP);System.out.println(for平均每次运行时间(ms) forAverageRunTime);}当数据量为10w测试5次的结果输出第1次stream 耗时81第1次for 耗时13第2次stream 耗时15第2次for 耗时23第3次stream 耗时7第3次for 耗时11第4次stream 耗时7第4次for 耗时13第5次stream 耗时9第5次for 耗时6list长度为100000 总共测试次数5stream总运行时间(ms) 119for总运行时间(ms) 66stream平均每次运行时间(ms) 23.80for平均每次运行时间(ms) 13.20当数据量为100w测试5次的输出结果第1次stream 耗时165第1次for 耗时1296第2次stream 耗时447第2次for 耗时62第3次stream 耗时363第3次for 耗时359第4次stream 耗时61第4次for 耗时350第5次stream 耗时389第5次for 耗时43list长度为1000000 总共测试次数5stream总运行时间(ms) 1425for总运行时间(ms) 2110stream平均每次运行时间(ms) 285.00for平均每次运行时间(ms) 422.00所有运行时长单位均为ms。综上测试结果当数据量少于百万级别的一次for循环来筛选数据效率更高当数据量达到八万级别还是使用stream来操作更加具有效率。但是小弟还是有点不明白原因是为何求高人指点一二