EpicPotato
EpicPotato

Reputation: 609

Is using get() excessively in Java inefficient?

I was wondering whether it was more efficient to use get() excessively on an object or store the return of the get() in a variable and use that. For example, would it be more efficient to do this:

someObject.setColor(otherObject.getColor().r, otherObject.getColor().g, 
         otherObject.getColor().b);

or to store the it in a variable like this

Color color = otherObject.getColor();
someObject.setColor(color.r, color.g, color.b);

Upvotes: 3

Views: 81

Answers (2)

Charchit
Charchit

Reputation: 43

In example#2

Color color = otherObject.getColor();
someObject.setColor(color.r, color.g, color.b);

you are only creating a reference to the original object, so you are not using any considerable "extra" memory. plus it is more readable so +1 for example#2

Upvotes: 1

wero
wero

Reputation: 32980

Option 1: you write the code as in example 1.

  • the java runtime might or might not optimize the code (to turn it into something like your example 2)
  • harder to read

Option 2: you write the code as in example 2.

  • does not rely on optimizations by the java runtime
  • easier to read

In my experience the runtime difference can be ignored (you can't measure the difference if not executed within a giant loop), but writing clean and understandable code is what counts.

Upvotes: 5

Related Questions