Java for loop 性能问题
2022-09-02 00:23:09
考虑这个例子:
public static void main(final String[] args) {
final List<String> myList = Arrays.asList("A", "B", "C", "D");
final long start = System.currentTimeMillis();
for (int i = 1000000; i > myList.size(); i--) {
System.out.println("Hello");
}
final long stop = System.currentTimeMillis();
System.out.println("Finish: " + (stop - start));
}
与
public static void main(final String[] args) {
final List<String> myList = Arrays.asList("A", "B", "C", "D");
final long start = System.currentTimeMillis();
final int size = myList.size();
for (int i = 1000000; i > size; i--) {
System.out.println("Hello");
}
final long stop = System.currentTimeMillis();
System.out.println("Finish: " + (stop - start));
}
这会造成任何差异吗?在我的机器上,第二个似乎执行得更快,但我不知道它是否真的准确。编译器会优化此代码吗?我可以认为,如果循环条件是一个不可变的对象(例如,String数组),他会这样做。