首先,我建议您使用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;
}
}
以下是典型运行的结果:
t1 time: 41412897
t2 time: 30580187
t3 time: 146536728
显然,使用 ArrayList 是 HashMap 的一大胜利(3-4 倍),至少对于我迭代 HashMap 的风格而言。我怀疑数组迭代器比数组下标慢的原因是需要创建所有迭代器对象然后进行垃圾收集。
作为参考,这是在具有大量可用内存的 Intel 1.6GHz 四核 Windows 机器上使用 Java 1.6.0_26(64 位 JVM)完成的。