In Java particularly Android development, is there any difference between declaring an object like
SomeObject object = new SomeObject();
someField.setObject(object);
compared to an anonymous object (not sure if that’s what is called)
someField.setObject(new SomeObject());
performance wise? Or improvements in memory. Thanks.
1
The code new SomeObject()
that you write is identical, and it will create identical byte code in both cases, so no, there is no difference with respect to the object creation.
Your examples differ only in what you do with the object: either assigning it to a local variable, or passing it as an argument to a function (which may then assign it to a local variable or a field). The only difference in performance can come from this distinction; e.g. an object stored only in a local variable can get garbage-collected once the scope ends, while an object passed outside the current scope may live longer, perhaps much longer. But that has nothing to do with object creation; it is equally true for old and new objects in your program. Therefore, whether to use temporary variables or nested invocations in your code is largely a matter of readability (which should be more important than optimization anyway, even if there was a difference).)
5