Is using get () overly inefficient in Java?
I was wondering if it was more efficient to use get () overly on an object, or to store the return of get () in a variable and use that. For example, it would be more efficient to do this:
someObject.setColor(otherObject.getColor().r, otherObject.getColor().g,
otherObject.getColor().b);
or store it in a variable like this
Color color = otherObject.getColor();
someObject.setColor(color.r, color.g, color.b);
+3
source to share
2 answers
Option 1: You write code like example 1.
- The java runtime may or may not optimize the code (to turn it into something like your example 2)
- harder to read
Option 2: you write code like example 2.
- does not rely on optimization with java runtime
- easier to read
In my experience, the runtime difference can be ignored (you can't measure the difference unless you run in a giant loop), but that's what clean, straightforward code thinks.
+5
source to share