HashMap中indexFor方法是用来查找数组下标的。在取数组下标的时候m&(lenth-1) 和m&length的值是一样的。
比如
m = 7 ,lenth=8那么7&8 =7
7的二进制表示为111,
111 & 111 = 111 =7
下面我们来看看在java代码中看看他们的执行时间如何
@Test public void test2() { int capacity = 32; int val = 13; int count = 2000; long t1 = System.nanoTime(); for (int i = 0; i < count; i++) { indexFor1(val,capacity); } long t2 = System.nanoTime(); System.out.println("& time:"+(t2-t1)); long t3 = System.nanoTime(); for (int i = 0; i < count; i++) { indexFor2(val,capacity); } long t4 = System.nanoTime(); System.out.println("% time:"+(t4-t3)); } static int indexFor1(int h, int length) { return h & (length-1); } static int indexFor2(int h, int length) { return h % (length); }
这是m =13,length =32
第一次 当执行2000次时
& time:104688
% time:134657
第二次 当执行20000次时
& time:806302
% time:879379
第三次 当执行200000次时
& time:2035873
% time:2359790
第四次 当执行2000000次时
& time:1945554
% time:2849155
第五次 当执行20000000次时
& time:1457010
% time:2105665
可以看到确实 & 比 % 好一点,说好多少,我确实不敢说,没次执行都是不同的,数据计算涉及到硬件的交互,准确的数据报告还需要权威给出,这个只做一个简单的探讨。