Recenlty I saw code (Java) like this:
myMethod(new Integer(123));
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));
However in this case, I think that there is no difference if I would use:
myMethod(123);
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)
will create a newObject
instance for each call.According to the javadoc,
Integer.valueOf(123)
has the difference it caches Objects... so you may (or may not) end up with the sameObject
if you call it more than once.For instance, the following code:
Has the following output:
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.Also take a look at Java's AutoBoxing if your method's signature uses
Integer
- when using it, the JVM will automatically callInteger.valueOf()
for you (therefore using the cache aswell).