Calling getters on an object vs. storing it as a local variable (memory footprint, performance)
I'd nearly always prefer the local variable solution.
Memory footprint
A single local variable costs 4 or 8 bytes. It's a reference and there's no recursion, so let's ignore it.
Performance
If this is a simple getter, the JVM can memoize it itself, so there's no difference. If it's a expensive call which can't be optimized, memoizing manually makes it faster.
Readability
Follow the DRY principle. In your case it hardly matters as the local variable name is character-wise as about as long as the method call, but for anything more complicated, it's readability as you don't have to find the 10 differences between the two expressions. If you know they're the same, so make it clear using the local variable.
Correctness
Imagine your SelectItem
does not accept null
s and your program is multithreaded. The value of listType.getDescription()
can change in the meantime and you're toasted.
Debugging
Having a local variable containing an interesting value is an advantage.
The only thing to win by omitting the local variable is saving one line. So I'd do it only in cases when it really doesn't matter:
- very short expression
- no possible concurrent modification
- simple private final getter
Java Method invocation vs using a variable
Never code for performance, always code for readability. Let the compiler do the work.
They can improve the compiler/runtime to run good code faster and suddenly your "Fast" code is actually slowing the system down.
Java compiler & runtime optimizations seem to address more common/readable code first, so your "Optimized" code is more likely to be de-optimized at a later time than code that was just written cleanly.
Note:
This answer is referring to Java code "Tricks" like the question referenced, not bad programming that might raise the level of loops from an O(N) to an O(N^2). Generally write clean, DRY code and wait for an operation to take noticeably too long before fixing it. You will almost never reach this point unless you are a game designer.
Java: saving to a variable vs multiple function calls
If getValue() is a timeconsuming operation it will most likely be better to call it once only and store the value in a variable.
If you call it several times, you might not in practice get any performance improvements, depending on compiler optimizations.
Performance of using a variable for input handling?
In terms of performance, the second is faster as it spares a duplicated processing.
But it is a so cheap task that you should execute it million times to see a difference.
Besides, modern JVMs performs many optimizations. Which could result in similar performance in both cases.
But in these two ways, I notice bad smells :
This way :
if (!textField.getText().equals("")) {
name = textField.getText();
}
introduces duplication.
It is generally unadvised as if we forget to change the duplicate everywhere we may introduce issues.
Duplicating one line of code is often not a serious issue but generally textfields are not single. So you perform very probably this task for multiple textfields. Duplication becomes so a problem.
This way :
String ipt = textField.getText();
if (!ipt.equals("")) {
name = ipt;
introduces a local variable that has a scope broader than required. It is also discouraged to make the code less error prone as we may reuse the variable after the processing where it is required while we should not be able to.
For your requirement, I dislike both solutions.
A better quality and efficient way would be introduce a method :
private String getValueOrDefault(TextField textField, String defaultValue) {
String value = textField.getText();
return !value.equals("") ? value : defaultValue;
}
You can invoke it in this way :
name = getValueOrDefault(textField, name);
You don't have any longer a variable that lives beyond its requirement and you don't have duplication either.
Performance of using a variable for input handling?
In terms of performance, the second is faster as it spares a duplicated processing.
But it is a so cheap task that you should execute it million times to see a difference.
Besides, modern JVMs performs many optimizations. Which could result in similar performance in both cases.
But in these two ways, I notice bad smells :
This way :
if (!textField.getText().equals("")) {
name = textField.getText();
}
introduces duplication.
It is generally unadvised as if we forget to change the duplicate everywhere we may introduce issues.
Duplicating one line of code is often not a serious issue but generally textfields are not single. So you perform very probably this task for multiple textfields. Duplication becomes so a problem.
This way :
String ipt = textField.getText();
if (!ipt.equals("")) {
name = ipt;
introduces a local variable that has a scope broader than required. It is also discouraged to make the code less error prone as we may reuse the variable after the processing where it is required while we should not be able to.
For your requirement, I dislike both solutions.
A better quality and efficient way would be introduce a method :
private String getValueOrDefault(TextField textField, String defaultValue) {
String value = textField.getText();
return !value.equals("") ? value : defaultValue;
}
You can invoke it in this way :
name = getValueOrDefault(textField, name);
You don't have any longer a variable that lives beyond its requirement and you don't have duplication either.
Java use getter in for loop or create a local variable?
As Rogério answered, getting the object reference outside the loop (Object object = example.getValue();
) will likely be faster (or will at least never be slower) than calling the getter inside the loop because
- in the "worst" case,
example.getValue()
might actually do some very computationally-expensive stuff in the background despite that getter methods are supposed to be "trivial". By assigning a reference once and re-using it, you do this expensive computation only once. - in the "best" case,
example.getValue()
does something trivial such asreturn value;
and so assigning it inside the loop would be no more expensive than outside the loop after the JIT compiler inlines the code.
However, more important is the difference in semantics between the two and its possible effects in a multi-threaded environment: If the state of the object example
changes in a way which causes example.getValue()
to return references to different objects, it is possible that, in each iteration, the method doSomething(Object object)
will actually operate on a different instance of Object
by directly calling doSomething(example.getValue());
. On the other hand, by calling a getter outside the loop and setting a reference to the returned instance (Object object = example.getValue();
), doSomething(object);
will operate on object
n times for n iterations.
This difference in semantics can cause behavior in a multi-threaded environment to be radically different from that in a single-threaded environment. Moreover, this need not be an actual "in-memory" multi-threading issue: If example.getValue()
depends on e.g. database/HDD/network resources, it is possible that this data changes during execution of the loop, making it possible that a different object is returned even if the Java application itself is single-threaded. For this reason, it is best to consider what you actually want to accomplish with your loop and to then choose the option which best reflects the intended behavior.
In Java is there a performance difference between referencing a field through getter versus through a variable?
Assuming that getSomethingElse()
is defined as
public SomethingElse getSomethingElse() {
return this.somethingElse;
}
performance difference will be minimal (or zero if it'll get inlined). However, in real life you can not always be sure that's the case - there may be some processing happening behind the scenes (not necessarily in the object itself but, say, via AOP proxy). So saving the result in the variable for repeat access may be a good idea.
Related Topics
What Are the Rules Dictating the Inheritance of Static Variables in Java
How to Find Out If "Debug Mode" Is Enabled
What Is the Jvm Thread Scheduling Algorithm
Java: Import Statement VS Fully Qualified Name
Maven Dependency for Servlet 3.0 API
How to Get a List from Some Class Properties with Java 8 Stream
Foreach VS Foreachordered in Java 8 Stream
Capturing Browser Logs with Selenium Webdriver Using Java
How to Use Classloader.Getresources() Correctly
Invalid Signature File Digest for Manifest Main Attributes Exception While Trying to Run Jar File
How to Make a List with Checkboxes in Java Swing
Is Autoboxing Possible for the Classes I Create
How to Quickly Determine If a Method Is Overridden in Java
Jackson: How to Add Custom Property to the JSON Without Modifying the Pojo
How to Enable the Java Keyword Assert in Eclipse Program-Wise