Time33算法与位运算

最近不是很忙,阅读了下《大型网站技术架构》一书。在4.3.4代码优化小节有这样的一句话:“目前比较好的字符串hash算法有Time33算法”。
Time33算法,就是hash(i)=33*hash(i-1)+str[i]。在jdk源码中String类的hashCode()方法使用的是Time31算法。
源码如下:
 public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}

Time33算法就是对字符串逐字符迭代乘以33。关于算法的名字笔者不再赘述,不过这里可能涉及到[color=red]用位运算来代替乘除运算以提高性能[/color]。

之前笔者在代码中看到位运算总是感觉看不懂,其实是出于性能的考虑。首先,我们来看下如何[color=red]实现乘除运算和位运算之间的转化:
a<<n 在数值上等同于 a*2^n
a>>n 在数值上等同于 a/2^n
比如 a*33 (33=2^5+1)用位运算可以写成 ((a<<5)+a)
[/color]

为什么要将乘除运算改为位运算呢?是由于位运算的性能要好一些,尤其在大规模计算的时候。如下代码:
public class Demo{
public static void main(String [] args){
long starttime=System.currentTimeMillis();
for(int i=0;i<10000;i++)
computeOne();
long endtime=System.currentTimeMillis();
System.out.println(endtime-starttime);
starttime=System.currentTimeMillis();
for(int i=0;i<10000;i++)
computeTwo();
endtime=System.currentTimeMillis();
System.out.println(endtime-starttime);
}
public static void computeOne(){
int result=10;
for(int i=0;i<10000000;i++){
if(i%2==0){
result=result*2;
}else{
result=result/2;
}
}
}
public static void computeTwo(){
int result=10;
for(int i=0;i<10000000;i++){
if(i%2==0){
result=(result<<1);
}else{
result=(result>>1);;
}
}
}
}

通过结果,可以知道位运算比乘除运算要快一些。

因此,对于String类的hashCode()方法,我们可以改成:
 public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = ((h<<5)-h) + val[i];
}
hash = h;
}
return h;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值