首先,我建議你使用一個HashMap
代替Hashtable
,出於同樣的原因,ArrayList
比Vector
一個更好的選擇:更少的開銷,由於沒用同步。
我的猜測是通過迭代ArrayList
會比通過由Hashtable
的(或HashMap
的)entrySet()
方法返回的Set
迭代更快。但要知道的唯一方法是配置文件。
顯然,對HashMap
的顯示列表的更改(除了添加或切斷最後一個元素)將比對ArrayList
更快。
編輯 所以我遵循了我自己的建議和基準。下面是我使用的代碼:
import java.util.*;
public class IterTest {
static class Thing {
Thing(String name) { this.name = name; }
String name;
}
static class ArrayIterTest implements Runnable {
private final ArrayList<Thing> list;
ArrayIterTest(ArrayList<Thing> list) {
this.list = list;
}
public void run() {
int i = 0;
for (Thing thing : list) {
++i;
}
}
}
static class ArraySubscriptTest implements Runnable {
private final ArrayList<Thing> list;
ArraySubscriptTest(ArrayList<Thing> list) {
this.list = list;
}
public void run() {
int i = 0;
int n = list.size();
for (int j = 0; j < n; ++j) {
Thing thing = list.get(j);
++i;
}
}
}
static class MapIterTest implements Runnable {
private final Map<String, Thing> map;
MapIterTest(Map<String, Thing> map) {
this.map = map;
}
public void run() {
int i = 0;
Set<Map.Entry<String, Thing>> set = map.entrySet();
for (Map.Entry<String, Thing> entry : set) {
++i;
}
}
}
public static void main(String[] args) {
final int ITERS = 10000;
final Thing[] things = new Thing[1000];
for (int i = 0; i < things.length; ++i) {
things[i] = new Thing("thing " + i);
}
final ArrayList<Thing> arrayList = new ArrayList<Thing>();
Collections.addAll(arrayList, things);
final HashMap<String, Thing> hashMap = new HashMap<String, Thing>();
for (Thing thing : things) {
hashMap.put(thing.name, thing);
}
final ArrayIterTest t1 = new ArrayIterTest(arrayList);
final ArraySubscriptTest t2 = new ArraySubscriptTest(arrayList);
final MapIterTest t3 = new MapIterTest(hashMap);
System.out.println("t1 time: " + time(t1, ITERS));
System.out.println("t2 time: " + time(t2, ITERS));
System.out.println("t3 time: " + time(t3, ITERS));
}
private static long time(Runnable runnable, int iters) {
System.gc();
long start = System.nanoTime();
while (iters-- > 0) {
runnable.run();
}
return System.nanoTime() - start;
}
}
,這裏是結果的一個典型運行:在一個HashMap
t1 time: 41412897
t2 time: 30580187
t3 time: 146536728
顯然使用一個ArrayList是一個巨大的勝利(按3-4倍) ,至少對於我通過HashMap迭代的風格來說。我懷疑數組迭代器比數組下標慢的原因是需要創建並隨後進行垃圾收集的所有迭代器對象。
作爲參考,這是在Intel 1.6GHz四核Windows機器上使用Java 1.6.0_26(64位JVM)完成的,該機器擁有充足的可用內存。
Absolutelly完美的答案,謝謝大的時候:) – 2011-12-15 01:18:24