我再上一篇文章的时候想过map的性能问题,没有仔细探究,今天有想到一个问题。
我们在使用HashMap的时候是用clear好呢,还是直接new一个比较好!
然后就写了点代码进行实验比较
Mapmap = new HashMap (); for (int i = 0; i < 100000; i++) { map.put(i+"", 1); } long start = System.currentTimeMillis(); map.clear(); map.put("headerId", 1); for (int i = 0; i < 100000; i++) { map.put(i+"", 1); } long end = System.currentTimeMillis(); System.out.println("运行时间:" + (end - start) + "毫秒"); long start2 = System.currentTimeMillis(); map = new HashMap (); map.put("headerId", 1); for (int i = 0; i < 100000; i++) { map.put(i+"", 1); } long end2 = System.currentTimeMillis(); System.out.println("运行时间:" + (end2 - start2) + "毫秒");
输出结果:
运行时间:37毫秒
运行时间:45毫秒
虽然时间差比较小,但事实证明如果后期大数据量的话还是clear效率比较高,如果是小数据量还是new效率高,1w条左右!