我在弦乐Java 6的源代码注意到的hashCode仅高速缓存的其它值大于0的性能差异由以下片断显示出:为什么String的hashCode()缓存0?
public class Main{
static void test(String s) {
long start = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
s.hashCode();
}
System.out.format("Took %d ms.%n", System.currentTimeMillis() - start);
}
public static void main(String[] args) {
String z = "Allocator redistricts; strict allocator redistricts strictly.";
test(z);
test(z.toUpperCase());
}
}
Running this in ideone.com给出以下输出:
Took 1470 ms.
Took 58 ms.
所以我的问题是:
- 为什么不串的hashCode()方法缓存0?
- Java字符串散列为0的概率是多少?
- 什么是避免每次散列值为0的字符串重新计算散列值的性能损失的最佳方法?
- 这是缓存值的最佳实践方式吗? (?IE缓存所有除一个)
为了您的娱乐,在这里每一行是一个字符串散列为0:
pollinating sandboxes
amusement & hemophilias
schoolworks = perversive
electrolysissweeteners.net
constitutionalunstableness.net
grinnerslaphappier.org
BLEACHINGFEMININELY.NET
WWW.BUMRACEGOERS.ORG
WWW.RACCOONPRUDENTIALS.NET
Microcomputers: the unredeemed lollipop...
Incentively, my dear, I don't tessellate a derangement.
A person who never yodelled an apology, never preened vocalizing transsexuals.
LOL! +1为一个很好的例子,做了übergeek的方式! – 2013-07-25 17:00:52