900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Java foreach与for循环性能对比

Java foreach与for循环性能对比

时间:2019-05-16 06:00:56

相关推荐

Java foreach与for循环性能对比

独角兽企业重金招聘Python工程师标准>>>

测试用例

List<String> list = new ArrayList<>();for (int i = 0; i < 10000000; i++) {list.add("value-" + i);}Long startTime = System.currentTimeMillis();for (String value : list) {if ("222".equals("222")) {if ("222".equals("222")) {if ("555".equals("555")) {if ("222".equals("222")) {value.concat("value");}}}}}Long endTime = System.currentTimeMillis();System.out.println(endTime - startTime);Long startTime2 = System.currentTimeMillis();for (int i = 0; i < list.size(); i++) {if ("222".equals("222")) {if ("222".equals("222")) {if ("222".equals("222")) {if ("222".equals("222")) {if ("222".equals("222")) {if ("222".equals("222")) {String value = list.get(i);value.concat("value" + i);}}}}}}}Long endTime2 = System.currentTimeMillis();System.out.println(endTime2 - startTime2);Long startTime3 = System.currentTimeMillis();for (int i = 0, length = list.size(); i < length; i++) {if ("888".equals("888")) {if ("888".equals("888")) {if ("888".equals("888")) {if ("888".equals("888")) {if ("888".equals("888")) {if ("888".equals("888")) {String value = list.get(i);value.concat("value" + i);}}}}}}}Long endTime3 = System.currentTimeMillis();System.out.println(endTime3 - startTime3);

执行结果

2455516533Process finished with exit code 0

总结

明确一个概念,对方法的调用,即使方法中只有一句语句,也是有消耗的,包括创建栈帧、调用方法时保护现场、调用方法完毕时恢复现场等。

尽量减少对变量的重复计算对性能有要求时,建议使用 for 循环。

谢谢各位看官评论。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。