【发布时间】:2013-11-22 12:16:57
【问题描述】:
如果我交换 HashMap 和 HashSet,我会得到不同的执行时间。首先出现的执行时间总是很高(HashMap/Hashset)。我不确定这背后的原因。任何帮助表示赞赏
执行 1 - 首先是 HashMap,然后是 HashSet --- 地图耗时:2071ms, 加起来耗时:794ms
执行 2 - 首先是 HashSet,然后是 HashMap --- 设置添加时间:2147ms, 加图耗时:781ms
private static Random secureRandom = new SecureRandom();
public static void main(String args[])
{
int testnumber = 1000000;
// HashMap
long starttimemap = System.currentTimeMillis();
Map<String, String> hashmap = new HashMap<String, String>();
for (int i = 0; i < testnumber; i++)
{
hashmap.put(Long.toHexString(secureRandom.nextLong()), "true");
}
long endtimemap = System.currentTimeMillis();
System.out.println("Time taken map add: " + (endtimemap - starttimemap) + "ms");
// HashSet
long starttimeset = System.currentTimeMillis();
Set<String> hashset = new HashSet<String>();
for (int i = 0; i < testnumber; i++)
{
hashset.add(Long.toHexString(secureRandom.nextLong()));
}
long endtimeset = System.currentTimeMillis();
System.out.println("Time taken set add: " + (endtimeset - starttimeset) + "ms");
}
【问题讨论】: