sne*_*ze1 7 java string lazy-initialization
它出现在java.lang.String.java中,Java只会在调用hashcode()之后生成哈希码,然后存储它,但为什么不在构造函数中创建哈希码呢?
相关代码:
if (h == 0 && count > 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
Run Code Online (Sandbox Code Playgroud)
大部分都可以放在构造函数中.
约书亚·布洛赫 (Joshua Bloch) 称这种做法为“活泼的单一检查”。
Jeremy Manson has excellent explanation of why it's done and why it'safe: on his blog
In essence, at construction time you save some time by skipping calculating hash code. In multithreaded environment you'll pay for this back because multiple thread potentially could do the same calculation.
| 归档时间: |
|
| 查看次数: |
899 次 |
| 最近记录: |