Java開発入門–ArrayListとLinkedList配列にForとIteratorを使って実行時間を計算する

javaコード:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class IteratorSampleFuncDemo {

public static long LoopsForCheck(List<String> list) {
long start = 0L, end = 0L;
@SuppressWarnings(“unused")
String ck = null;
start = System.nanoTime();
for (int i = list.size() – 1; i >= 0; –i) {
ck = list.get(i);
}
end = System.nanoTime();
return end – start;
}

public static long IteratorCheckFunc(List<String> list) {
long start = 0L, end = 0L;
@SuppressWarnings(“unused")
String ck = null;
start = System.nanoTime();
Iterator<String> it = list.iterator();
while (it.hasNext()) {
ck = it.next();
}
end = System.nanoTime();
return end – start;
}

public static void main(String[] args) {

final int lstLen = 20000;
List<String> arraylist = new ArrayList<String>();
List<String> linkedlist = new LinkedList<String>();
for (int i = 0; i < lstLen; ++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(“Test Result as Follows");
System.out.println(“List\t\tType\t\tTime(nanoseconds)");
System.out.println(“————————————————-“);
System.out.printf(FORMAT, “ArrayList", “For", LoopsForCheck(arraylist));
System.out.printf(FORMAT, “ArrayList", “Iterator", IteratorCheckFunc(arraylist));
System.out.printf(FORMAT, “LinkedList", “For", LoopsForCheck(linkedlist));
System.out.printf(FORMAT, “LinkedList", “Iterator", IteratorCheckFunc(linkedlist));
}

}

実行結果
Test Result as Follows
List Type Time(nanoseconds)
————————————————-
ArrayList For 2113920
ArrayList Iterator 1917363
LinkedList For 617852031
LinkedList Iterator 1624393

Java

Posted by arkgame