In Java particularly Android development, is there any difference between declaring an object like

SomeObject object = new SomeObject();

compared to an anonymous object (not sure if that's what is called)

someField.setObject(new SomeObject());

performance wise? Or improvements in memory. Thanks.

  • 4
    this is not an anonymous object :) and no there is zero difference apart from readability. – MattDavey Oct 10 '12 at 7:26

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).)

  • 3
    +1 for "a matter of readability, which should be more important than optimization anyway" – MattDavey Oct 10 '12 at 7:31
  • 1
    The problem in this case is that readability of temporary variables is extremely subjective. Some people (like me) prefer shorter code and thus use nested invocations whenever possible while other people need a name for everything and thus make lots of temporary variables. – Jan Hudec Oct 10 '12 at 7:35
  • So that's what you call it, nested invocations? Thanks for the answer. – userIsAMonkey Oct 10 '12 at 7:45
  • @userIsAMonkey: that's not a name, it's simply a description of what's happening here. – Joachim Sauer Oct 10 '12 at 7:55
  • @JanHudec I agree, for short methods (which people should be aiming for, in any event), the explicit naming of an object is unnecessary and decreases the signal to noise ratio. That said, a good name in non-obvious situations can make all the difference. I personally don't subscribe to the "two lines, because then it's easier to step through" logic - if you're continuously stepping through those two lines, something's not right, and you can always make that change as you need it. – Daniel B Oct 10 '12 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.