【发布时间】:2015-10-19 11:48:07
【问题描述】:
我想知道有什么不同,我在编写代码时应该注意什么。
- 测试时使用相同的参数和方法
put(),get()无需打印 - 使用
System.NanoTime()测试运行时 - 我尝试使用具有 10 个值的 1-10 个 int 键,因此每个哈希都返回唯一索引,这是最佳方案
- 我基于此的 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,则该问题是不完整的。您还应该展示您的微基准,因为其中的小错误会完全扭曲结果。
标签: java performance hashmap runtime