The scenario is that I need to access a value at least twice. I.e. I am using logger to keep track of what is happening in the application. I want to log the name of the object, that function is working on, and later on do something with the very same name(i.e check if it contains some string or put it into an array).
Storing the name in variable:
foo(Bar bar){
String name = bar.getName();
logger.info("I am working with "+name);
this.doSomethingWith(name);
}
Or calling getName() twice:
foo(Bar bar){
logger.info("I am working with "+bar.getName());
this.doSomethingWith(bar.getName());
}
I understand, that in the first scenario, I will create a new String, assign a value to it and then retrieve this value twice. This way I am using more memory resources, correct?
In second scenario, am I accessing object bar twice and then accessing it's name twice. I suppose this is not a DRY approach. But on the other hand I am not repeating myself in the memory, correct?
Which approach is better?
You are not using more memory in the first example, because String
is an immutable object. As such, any reference to a String is simply a pointer to the same object in memory.
The latter option also has some issues of thread safety where the result of getName()
might change between invocations. Though possibly unlikely, it is something you might want to take into consideration.
With that in mind, I would recommend the first option even though it is more "talky."
Note: It is also possible that getName()
is generated by computation, in which case you would actually end up with the second method using more memory than the first one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With