简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM