package test; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Test9 { public static void main(String[] args) { Set<Dog> set = new HashSet<>(); for (int i = 0; i < 10_000_000; i++) { set.add(new Dog(i, "dog" + i)); } long nanoTime = System.nanoTime(); test1(set); long nanoTime1 = System.nanoTime(); test2(set); long nanoTime2 = System.nanoTime(); test3(set); long nanoTime3 = System.nanoTime(); test4(set); long nanoTime4 = System.nanoTime(); System.out.println((nanoTime1 - nanoTime) / 1000000.0); System.out.println((nanoTime2 - nanoTime1) / 1000000.0); System.out.println((nanoTime3 - nanoTime2) / 1000000.0); System.out.println((nanoTime4 - nanoTime3) / 1000000.0); } public static void test1(Set<Dog> list) { Iterator<Dog> iterator = list.iterator(); while (iterator.hasNext()) { iterator.next().hashCode(); } } public static void test2(Set<Dog> list) { for (Dog dog : list) { dog.hashCode(); } } public static void test3(Set<Dog> list) { list.forEach(dog -> { dog.hashCode(); }); } public static void test4(Set<Dog> list) { list.iterator().forEachRemaining(dog -> { dog.hashCode(); }); } } View Code
经过计算得出如下结果:
不难发现,java8的foreach依然每次耗时100ms以上,最快的变成了增强for循环,Iterator遍历和java8的iterator().forEachRemaining差不多。
3.最后遍历Map依然使用相同的方式测试Map集合遍历,测试类如下: