Java 遍历速度例子。 引用。

 
  
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)); } }


你可能感兴趣的:(Java 遍历速度例子。 引用。)