我想知道是什麼改變了我在編寫代碼時應該知道什麼。爲什麼我的HashMap實現比JDK慢10倍?
- 使用相同的參數和方法
put()
,get()
而不打印 - 用於
System.NanoTime()
測試運行時 - 我具有1-10 INT鍵試圖將其與10個值測試 時,所以每一個單個散列返回獨特的索引,這是最優化的場景
- 基於此的HashSet實現幾乎與JDK的一樣快速
這裏是我的簡單的實現:
public MyHashMap(int s) {
this.TABLE_SIZE=s;
table = new HashEntry[s];
}
class HashEntry {
int key;
String value;
public HashEntry(int k, String v) {
this.key=k;
this.value=v;
}
public int getKey() {
return key;
}
}
int TABLE_SIZE;
HashEntry[] table;
public void put(int key, String value) {
int hash = key % TABLE_SIZE;
while(table[hash] != null && table[hash].getKey() != key)
hash = (hash +1) % TABLE_SIZE;
table[hash] = new HashEntry(key, value);
}
public String get(int key) {
int hash = key % TABLE_SIZE;
while(table[hash] != null && table[hash].key != key)
hash = (hash+1) % TABLE_SIZE;
if(table[hash] == null)
return null;
else
return table[hash].value;
}
這裏的風向標:
public static void main(String[] args) {
long start = System.nanoTime();
MyHashMap map = new MyHashMap(11);
map.put(1,"A");
map.put(2,"B");
map.put(3,"C");
map.put(4,"D");
map.put(5,"E");
map.put(6,"F");
map.put(7,"G");
map.put(8,"H");
map.put(9,"I");
map.put(10,"J");
map.get(1);
map.get(2);
map.get(3);
map.get(4);
map.get(5);
map.get(6);
map.get(7);
map.get(8);
map.get(9);
map.get(10);
long end = System.nanoTime();
System.out.println(end-start+" ns");
}
如果沒有測試顯示比較的另一端,即使用'HashMap',問題是不完整的。你還應該展示你的微基準,因爲這些微小的錯誤是完全錯誤的結果。 – dasblinkenlight