Java foreach与for循环性能对比

测试用例

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);

执行结果

2455
516
533

Process finished with exit code 0

总结

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

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

谢谢各位看官评论。

猜你喜欢

转载自my.oschina.net/u/1033181/blog/1796371