0

What is the difference between the codes below?

Alternative 1:

QuickAction quickAction = new QuickAction();
quickAction.changeFormField();

Alternative 2:

new QuickAction().changeFormField();

I think the Alternative 1 is better if I call only a single method, because it don't use a new memory address to the variable. If I call 2 or more methods, I can create a variable and assign the new object. Is it correct?

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47
  • 3
    That "memory address" storage is like 4 bytes on a method stack frame. Don't let that be your concern. Use the 2nd option because you're telling other readers the `QuickAction` instance is no longer needed. – Savior Feb 08 '18 at 17:31
  • 1
    *"I think the Alternative 1 is better if I will call just and just only a method..."* Pretty sure you meant Alternative 2 there. – T.J. Crowder Feb 08 '18 at 17:32
  • Depends if you need `quickAction` later or not. If yes, use 1). If no, use 2). It's a readability question, not an optimization. Let the compiler or the JVM do the optimization for you. – gaborsch Feb 08 '18 at 17:32
  • 1
    @Pillar: If the JVM doesn't optimize that away. – T.J. Crowder Feb 08 '18 at 17:32
  • 3
    You've tagged your question [tag:instance-variables] but what you've shown is just a local variable, not an instance variable. It makes a big difference to the question. – T.J. Crowder Feb 08 '18 at 17:34

0 Answers0