测试代码:
public static void main(String[] args) {
Map map=new HashMap();
User user=new User(1L,"san",2,"wuhan ","2",true);
ConcurrentMap map1=new ConcurrentHashMap();
int j=10000;
int i=0;
long a = System.currentTimeMillis();
while (i<j){
Object put = map.put("use" + i, user);
i++;
}
long b = System.currentTimeMillis();
System.out.println("map存花费时间"+(b-a)+"毫秒");
i=0;
while (i<j){
Object object = map.get("use" + i);
i++;
}
long c = System.currentTimeMillis();
System.out.println("map取花费时间"+(c-b)+"毫秒");
i=0;
while (i<j){
Object put = map1.put("use" + i, user);
i++;
}
long d=System.currentTimeMillis();
System.out.println("currmap存花费时间"+(d-c)+"毫秒");
i=0;
while (i<j){
Object object = map1.get("use" + i);
i++;
}
long f=System.currentTimeMillis();
System.out.println("currmap取花费时间"+(f-d)+"毫秒");
}
当数据量为一万时:
map存花费时间11毫秒 12 9 11 10 去掉最高最低后取平均 10.6
map取花费时间5毫秒 5 4 3 4 去掉最高最低后取平均 4.6
currmap存花费时间18毫秒 11 11 11 9 去掉最高最低后取平均 11
currmap取花费时间5毫秒 3 5 3 4 去掉最高最低后取平均 4.6
当数据量为十万时:
map存花费时间63毫秒 56 57 61 67 去掉最高最低后取平均 60.3
map取花费时间18毫秒 25 18 20 21 去掉最高最低后取平均 19.6
currmap存花费时间43毫秒 49 51 49 54 去掉最高最低后取平均 49.6
currmap取花费时间12毫秒 14 12 16 13 去掉最高最低后取平均 13
当数据量为百万时:
map存花费时间346毫秒 218 192 211 193 去掉最高最低后取平均 207.3
map取花费时间406毫秒 492 456 549 482 去掉最高最低后取平均 476.6
currmap存花费时间674毫秒 697 632 762 214 去掉最高最低后取平均 667.6
currmap取花费时间131毫秒 137 161 155 581 去掉最高最低后取平均 151
当数据量500万时候:
map存花费时间2783毫秒 3269 3239 3150 3241 去掉最高最低后取平均 3210
map取花费时间729毫秒 677 664 669 661 去掉最高最低后取平均 670
currmap存花费时间3036毫秒 2721 2848 2678 2733 去掉最高最低后取平均2767.3
currmap取花费时间786毫秒 808 2546 771 1879 去掉最高最低后取平均 1157.6
当数据量为千万时:
map存花费时间7803毫秒 7786 9094 7168 9756 去掉最高最低后取平均 8227.6
map取花费时间6323毫秒 1195 3780 4140 4489 去掉最高最低后取平均 4136.3
currmap存花费时间5057毫秒 7021 6895 4986 7231 去掉最高最低后取平均 6300
currmap取花费时间4741毫秒 1349 1064 5120 1192 去掉最高最低后取平均 2427.3
当数据量为亿时: 内存不够
结论:
ConcurrentMap存取的效率在数量小和数据量大的时候都一直都比较优越,就是在数据量在500万左右时候浮动较大,
而且ConcurrentMap是线程安全的.建议使用 ConcurrentMap的key和value都不允许为空