問題描述
最近我看到這樣的代碼(Java):
Recenlty I saw code (Java) like this:
myMethod(new Integer(123));
我目前正在重構(gòu)一些代碼,Sonar 工具中有一個(gè)提示,使用這樣的東西對(duì)內(nèi)存更友好:
I am currently refactoring some code, and there is a tip in Sonar tool, that it's more memory friendly to use sth like this:
myMethod(Integer.valueOf(123));
但是在這種情況下,我認(rèn)為如果我會(huì)使用沒有區(qū)別:
However in this case, I think that there is no difference if I would use:
myMethod(123);
我可以理解,如果我將變量傳遞給方法,但硬編碼 int?或者如果會(huì)有 Long/Double 等,我想要 Long 表示數(shù)字.但是整數(shù)?
I could understand that, if I would pass a variable to the method, but hard coded int? Or if there would be Long/Double etc and I want Long representation of number. But integer?
推薦答案
new Integer(123)
將為每個(gè)調(diào)用創(chuàng)建一個(gè)新的 Object
實(shí)例.
new Integer(123)
will create a new Object
instance for each call.
根據(jù) javadoc, Integer.valueOf(123)
不同之處在于它緩存對(duì)象......所以如果你調(diào)用它更多,你可能(或可能不會(huì))最終得到相同的 Object
不止一次.
According to the javadoc, Integer.valueOf(123)
has the difference it caches Objects... so you may (or may not) end up with the same Object
if you call it more than once.
比如下面的代碼:
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = new Integer(1);
System.out.println("a==b? " + (a==b));
Integer c = Integer.valueOf(1);
Integer d = Integer.valueOf(1);
System.out.println("c==d? " + (c==d));
}
有以下輸出:
a==b? false
c==d? true
至于使用 int
值,您使用的是原始類型(考慮到您的方法也在其簽名上使用原始類型) - 它會(huì)使用更少的內(nèi)存并且可能更快,但是您例如,不能將其添加到收藏中.
As to using the int
value, you are using the primitive type (considering your method also uses the primitive type on its signature) - it will use slightly less memory and might be faster, but you won't be ale to add it to collections, for instance.
如果您的方法的簽名,還請(qǐng)查看 Java 的 AutoBoxing使用 Integer
- 使用時(shí),JVM 會(huì)自動(dòng)為您調(diào)用 Integer.valueOf()
(因此也使用緩存).
Also take a look at Java's AutoBoxing if your method's signature uses Integer
- when using it, the JVM will automatically call Integer.valueOf()
for you (therefore using the cache aswell).
這篇關(guān)于new Integer(123)、Integer.valueOf(123) 和 just 123 之間的區(qū)別的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!