問題描述
在閱讀HashMap
的源代碼時,我在public V put(K key, V value)
中看到了這個片段:
While reading the source code for HashMap
, I came across this snippet in public V put(K key, V value)
:
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
為什么要將 e.key
分配給 k
進行比較?為什么不直接比較,比如:
Why assign e.key
to k
for comparing? Why not compare directly, like:
if (e.hash == hash && (e.key == key || key.equals(e.key))
-------- 更新 ------------
------------------- UPDATE ------------------------
根據@seand的回答,我做了更詳細的調查:
According to the answer from @seand, I do more detail investigation:
import com.test.Test;
public class Main {
public static void main(String[] args) {
Test t = new Test();
int a = t.a;
int b = a;
}
}
類 Test 有一個 int 字段;
class Test has a int filed a;
使用 javap -c Main 獲取類文件內容:
Using javap -c Main to get the class file content:
public static void main(java.lang.String[]);
Code:
0: new #2 // class test/Test
3: dup
4: invokespecial #3 // Method test/Test."<init>":()V
7: astore_1
8: aload_1
9: getfield #4 // Field test/Test.a:I
12: istore_2
13: iload_2
14: istore_3
15: return
int a = t.a
表示
8:[load the t object]
9:[access the field a]
12:[store the value to a]
參考jvm規范獲取[getfield的信息]
Refer to jvm specification get information of [getfield]
int b = a
表示:
13:[load the local variable]
14:[store the value to b];
訪問局部變量似乎比訪問類字段更合理.
It seems reasonable to access the local variable than the class field.
推薦答案
我猜這是一種優化,可以節省對 e.key 的額外查找.(雖然它實際上不是使用invokevirtual 的方法調用,但它可以節省一定程度的間接性).由于這是一個使用非常頻繁的庫函數,作者可能會使用他們能想到的所有技巧來獲得最大性能.您還可以看到它如何在 k = e.key
中檢查對象身份,這可以避免成本稍高的 equals()
調用.
My guess is it's an optimization which saves an extra lookup to e.key. (Though it's not actually a method call that's using invokevirtual, it may save a level of indirection). Since this is a very heavily used library function the authors likely used every trick they could think of for maximum performance. You can also see how it checks for object identity in k = e.key
which may avoid a slightly more costly equals()
call.
這篇關于為什么不直接比較 e.key 而不是將其分配給變量?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!