首先,建议您使用
HashMap
而不是
Hashtable
,原因与使用
ArrayList
比使用
Vector
相同:由于无用的同步,开销更小。
我猜遍历
ArrayList
比遍历
Hashtable
(或
HashMap
)的
entrySet()
方法返回的
Set
更快。但唯一知道的方法是进行分析。
显然,对于
HashMap
,除了附加或削减最后一个元素之外,对显示列表的更改将更快。
编辑
所以我遵循了自己的建议并进行了基准测试。这是我使用的代码:
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
显然,对于我的HashMap迭代方式来说,使用ArrayList比HashMap更优(优势为3-4倍)。我猜测数组迭代器比数组下标访问慢的原因是因为需要创建并回收许多迭代器对象。
参考信息:这是在Java 1.6.0_26(64位JVM)上,在一台拥有充足空闲内存的英特尔1.6 GHz四核Windows计算机上完成的。