概述
更好的方法是使用OpenJDK JMH框架进行基准测试,因为它将自动处理JVM的预热问题,请参见此示例– Java JMH基准教程 一个简单的Java代码来测试以下循环方法的性能: 在Java中,只需比较endTime和startTime即可获得函数的经过时间。 循环包含1、5、10和1500万条记录的 输出量 迭代器循环最慢,并且for循环和while循环之间的差异并不明显。 翻译自: https://mkyong.com/java/while-loop-for-loop-and-iterator-performance-test-java/
节点
本文使用endTime - startTime
方法来测量循环的性能,它忽略了JVM预热优化,其结果可能不一致或准确。
long startTime = new Date().getTime();
// call something else
long endTime = new Date().getTime();
long difference = endTime - startTime;
System.out.println("Elapsed time in milliseconds: " + difference);
While vs For vs迭代器
List
Java代码。 package com.mkyong.benchmark.bk;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class LoopSimpleTest {
private static List<String> DATA_FOR_TESTING = Arrays.asList(createArray());
public static void main(String[] argv) {
LoopSimpleTest obj = new LoopSimpleTest();
obj.loopIterator();
obj.loopFor();
obj.loopWhile();
}
public void loopFor() {
System.out.println("n--------- For Loop -------n");
long startTime = new Date().getTime();
for (int i = 0; i < DATA_FOR_TESTING.size(); i++) {
String s = DATA_FOR_TESTING.get(i);
}
long endTime = new Date().getTime();
long difference = endTime - startTime;
System.out.println("For - Elapsed time in milliseconds: " + difference);
}
public void loopWhile() {
System.out.println("n--------- While Loop -------n");
long startTime = new Date().getTime();
int i = 0;
while (i < DATA_FOR_TESTING.size()) {
String s = DATA_FOR_TESTING.get(i);
i++;
}
long endTime = new Date().getTime();
long difference = endTime - startTime;
System.out.println("While - Elapsed time in milliseconds: " + difference);
}
public void loopIterator() {
System.out.println("n--------- Iterator Loop -------n");
long startTime = new Date().getTime();
Iterator<String> iterator = DATA_FOR_TESTING.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
}
long endTime = new Date().getTime();
long difference = endTime - startTime;
System.out.println("Iterator - Elapsed time in milliseconds: " + difference);
}
private static String[] createArray() {
String sArray[] = new String[15_000_000];
for (int i = 0; i < 15_000_000; i++) {
sArray[i] = "Array " + i;
}
return sArray;
}
}
D:test>java -Xms1024m -Xmx1024m ArrayToList
--------- Iterator Loop -------
Iterator - Elapsed time in milliseconds: 390
--------- For Loop --------
For - Elapsed time in milliseconds: 234
--------- While Loop -------
While - Elapsed time in milliseconds: 234
参考文献
最后
以上就是幽默冷风为你收集整理的Java – While vs For vs Iterator性能测试的全部内容,希望文章能够帮你解决Java – While vs For vs Iterator性能测试所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复