一个完整的遍历速度测试:
import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; /** * IteratorTest * @author SageZk */ public class IteratorTest { public static long testForloops(List<String> list) { long start = 0L, end = 0L; @SuppressWarnings("unused") String le = null; start = System.nanoTime(); for (int i = list.size() - 1; i >= 0; --i) { le = list.get(i); } end = System.nanoTime(); return end - start; } public static long testIterator(List<String> list) { long start = 0L, end = 0L; @SuppressWarnings("unused") String le = null; start = System.nanoTime(); Iterator<String> it = list.iterator(); while (it.hasNext()) { le = it.next(); } end = System.nanoTime(); return end - start; } public static void main(String[] args) { //测试列表长度 final int LEN = 10000; //初始化测试用数据 List<String> arraylist = new ArrayList<String>(); List<String> linkedlist = new LinkedList<String>(); for (int i = 0; i < LEN; ++i) { String s = Integer.toString(i, 2); arraylist.add(s); linkedlist.add(s); } //打印测试结果 final String FORMAT = "%1$-16s%2$-16s%3$16d/n"; System.out.println("List/t/tType/t/tTime(nanoseconds)"); System.out.println("-------------------------------------------------"); System.out.printf(FORMAT, "ArrayList", "for", testForloops(arraylist)); System.out.printf(FORMAT, "ArrayList", "Iterator", testIterator(arraylist)); System.out.printf(FORMAT, "LinkedList", "for", testForloops(linkedlist)); System.out.printf(FORMAT, "LinkedList", "Iterator", testIterator(linkedlist)); } }
以下是 3 组测试结果:
BatchFile code List Type Time ( nanoseconds ) ------------------------------------------------- ArrayList for 1189258 ArrayList Iterator 2365594 LinkedList for 152396254 LinkedList Iterator 2340801 List Type Time ( nanoseconds ) ------------------------------------------------- ArrayList for 1235701 ArrayList Iterator 4249982 LinkedList for 149825606 LinkedList Iterator 2525531 List Type Time ( nanoseconds ) ------------------------------------------------- ArrayList for 1198267 ArrayList Iterator 2584617 LinkedList for 150382451 LinkedList Iterator 2347994