我在网上遇到了一个算法http://www.coderanch.com/t/201836/Performance/java/Hashtable-vs-Hashmap 并决定测试它
public class MapTest{
static int sizeOfTrial = 100000;
static String[] keys = new String[sizeOfTrial];
static String[] vals = new String[sizeOfTrial];
public static void main(String[] args) {
//init sizeOfTrial key/value pairs
for (int i=0; i < sizeOfTrial; i++){
String s1 = "key"+ i;
String s2 = "val"+ i;
keys[i] = s1;
vals[i] = s2;
}
test(new TreeMap(), "TreeMap");
test(new Hashtable(), "Hashtable");
test(new HashMap(), "HashMap");
test(new Hashtable(200000), "Hashtable presized");
test(new HashMap(200000), "HashMap presized");
}
public static void test(Map tm, String name){
long t1 = System.currentTimeMillis();
for (int i=0; i < sizeOfTrial; i++){
tm.put(keys[i],vals[i]);
}
for (int i=0; i < sizeOfTrial; i++){
tm.get(keys[i]);
}
long t2 = System.currentTimeMillis();
System.out.println("total time for " + name + ": " + (t2-t1));
}
}
我得到了以下结果
total time for TreeMap: 1744
total time for Hashtable: 446
total time for HashMap: 234
total time for Hashtable presized: 209
total time for HashMap presized: 196
这个 JVM 是独立的和任意的,还是真的提供了更快的访问和存储时间?