Reputation: 609
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
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
Reputation: 32980
Option 1: you write the code as in example 1.
Option 2: you write the code as in example 2.
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