首先,我建议你使用一个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