0
假設我有一個java類(我們將調用ThatClass
),它有很多靜態final字段(儘管它們都不是value字段),並且假設我從很多方法訪問很多這些字段我們將稱之爲ThisClass
。考慮到內存使用和性能都至關重要的情況,是否值得將在ThisClass
的方法中使用的ThatClass
的靜態最終字段存儲爲ThisClass
中的字段?在Java中,是否值得將另一個類的字段存儲在我的類的字段中?
例子:
public class ThatClass
{
public static final Foo field1 = new Foo();
public static final Foo field2 = new Foo();
public static final Foo field3 = new Foo();
}
//implementation A
public class ThisClass
{
public ThisClass()
{
for (int i = 0; i < 20; ++i)
{
Bar(ThatClass.field1, ThatClass.field2, ThatClass.field3);
}
}
public void Bar(Foo arg1, Foo arg2, Foo arg3)
{
// do something.
}
/* imagine there are even other methods in ThisClass that need to access the
* fields of ThatClass.
*/
}
現在這個其他實施ThisClass
//implementation B
public class ThisClass
{
private final Foo myField1;
private final Foo myField2;
private final Foo myField3;
public ThisClass()
{
myField1 = ThatClass.field1;
myField2 = ThatClass.field2;
myField3 = ThatClass.field3;
for (int i = 0; i < 20; ++i)
{
Bar(myField1, myField2, myField3);
}
}
public void Bar(Foo arg1, Foo arg2, Foo arg3)
{
// do something.
}
/* imagine there are even other methods in ThisClass that need to access the
* fields of ThatClass.
*/
}
我知道我不會需要通過三個字段作爲參數在執行B中的方法Bar
,但對於爲了這個討論,想象這是必要的。
問題:
有沒有關於這兩種實現之間的性能有什麼區別? B比A快嗎?
關於內存成本,B要求比A更多的內存?我會想象它,但只是多一點(一個額外的參考B的每個額外的領域,每個參考是一個整數的大小,對吧?)
謝謝!
實施測試並對其進行測量。訪問靜態字段*的開銷可能包括緩存未命中,但實際上我懷疑你會看到任何可衡量的好處 –
如果有的話,在兩個地方複製字段會降低性能(由於緩存未命中)並增加內存使用。訪問一個靜態字段需要花費相同的時間,無論它是否在你的課堂上。 –
你認爲性能差異來自哪裏?您正在將相同的參考文件複製到另一個地址,這有什麼幫助? –