先说结论:
对于遍历一个1千万条数据的arrayList,fori循环最快,iterator其次,foreach再其次,forStream最慢。
测试代码
public class ForSpeedTest {
// private static final long FOR_COUNT = 10000_0000;
private static final long FOR_COUNT = 1000_0000;
// private static final long FOR_COUNT = 100_0000;
// private static final long FOR_COUNT = 10_0000;
// private static final long FOR_COUNT = 1_0000;
// private static final long FOR_COUNT = 100;
private static List<String> arrayList = new ArrayList<>();
static {
//数据准备
for (int i = 0; i < FOR_COUNT; i++) {
arrayList.add("abc" + i);
}
}
public static void main(String[] args) throws Exception{
Thread.sleep(1000);
StopWatch stopWatch = new StopWatch();
stopWatch.start("forI");
forI();
stopWatch.stop();
stopWatch.start("forEach");
forEeach();
stopWatch.stop();
stopWatch.start("forStream");
forStream();
stopWatch.stop();
stopWatch.start("forI2");
forI2();
stopWatch.stop();
stopWatch.start("iterator");
forIterator();
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}
private static void forI() {
long size = arrayList.size();
for (int i = 0; i < size; i++) {
}
}
private static void forEeach() {
for (String s : arrayList) {
}
}
private static void forStream() {
arrayList.forEach(x -> {
});
}
private static void forI2() {
for (int i = 0; i < arrayList.size(); i++) {
}
}
private static void forIterator() {
Iterator<String> iterator = arrayList.iterator();
while(iterator.hasNext()){
iterator.next();
}
}
}