Time33算法与位运算

来源:互联网 发布:路由器百兆和千兆知乎 编辑:程序博客网 时间:2024/04/30 12:55
最近不是很忙,阅读了下《大型网站技术架构》一书。在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。关于算法的名字笔者不再赘述,不过这里可能涉及到用位运算来代替乘除运算以提高性能

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


为什么要将乘除运算改为位运算呢?是由于位运算的性能要好一些,尤其在大规模计算的时候。如下代码:
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;    }

0 0