[size=medium]今早在团队内分享了<通过 HashMap、HashSet 的源代码分析其 Hash 存储机制>,觉得自己又对hashMap的存储机制加深了了解,在分享会上大家讨论讨论的其中一个问题是:hashMap里的indexFor(int h, int length)方法为何不用取模的方式实现而是用&运算实现?当时讨论的结果是%运算比&运算更加耗费时间,下来之后我写了一个方法来印证一下:
最终得到的结果是:无论是用%还是&运算,都可以根据hash值来得到在table中相同的索引位置,但是如果需要被运算的hash值足够多的话,&运算的效率比%运算要高很多,上面的代码里反复执行了1W次,结果都是&运算比较节省时间。[/size]
package com.tina.jdk;
/**
* @author tina.wyn
*
*/
public class TestIndexFor {
static int indexForWith(int h,int length){
return h & (length-1);
}
static int indexForWithMod(int h,int length){
return h % length;
}
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
for (int time = 0; time < 100000; time++) {
for (int i = 0; i < 100; i++) {
int a = indexForWith(i,16);
// System.out.println(a);
}
}
long t2 = System.currentTimeMillis();
System.out.println("使用与运算所耗时间为:"+(t2-t1) );
long t3 = System.currentTimeMillis();
for (int time = 0; time < 100000; time++) {
for (int j = 0; j < 100; j++) {
int b = indexForWithMod(j,16);
// System.out.println(b);
}
}
long t4 = System.currentTimeMillis();
System.out.println("使用模所耗时间为:"+(t4-t3) );
}
}
result:
使用与运算所耗时间为:16
使用模所耗时间为:31
------------------------------
使用与运算所耗时间为:0
使用模所耗时间为:47
------------------------------
使用与运算所耗时间为:16
使用模所耗时间为:47
最终得到的结果是:无论是用%还是&运算,都可以根据hash值来得到在table中相同的索引位置,但是如果需要被运算的hash值足够多的话,&运算的效率比%运算要高很多,上面的代码里反复执行了1W次,结果都是&运算比较节省时间。[/size]