2020-12-10

currentHashMap定位获取指定index的Node

static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
        return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
    }

i是获取的Node在数组中的索引值

正常的处理是采用arrayBaseOffset + i *arrayIndexScale

此处采用arrayBaseOffset +i<<(31 - Integer.numberOfLeadingZeros(arrayIndexScale))

首先有个前提,arrayIndexScale是2的整数次幂

int scale = U.arrayIndexScale(ak);
if ((scale & (scale - 1)) != 0)
    throw new Error("data type scale not a power of two");

证明 i *arrayIndexScale == i<<(31 - Integer.numberOfLeadingZeros(arrayIndexScale))

假设arrayIndexScale = 2^n

即证明n = 31 - Integer.numberOfLeadingZeros(arrayIndexScale)

Integer.numberOfLeadingZeros(arrayIndexScale) = 32 - (n +1) = 31 -n

相等

 

采用等价的位运算相必是为了提升效率,但是实测好像并不能提升效率

int scale = 1<<2;  //scale 是2的整数幂
		
long s1 = System.nanoTime();
for(int i =0;i<10000;i++) {
	int j = scale * i ;
}
long s2 = System.nanoTime();
for(int i =0;i<10000;i++) {
	int j = i << (31 - Integer.numberOfLeadingZeros(scale));
}
long s3 = System.nanoTime();
System.out.println(s2 - s1);
System.out.println(s3 - s2);

结果

70907
372259

反而采用位运算的耗时更长,不排除偶然性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值