Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables to store values or directly get values from the objects?

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?

like image 440
user1581900 Avatar asked Oct 05 '12 13:10

user1581900


1 Answers

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.

like image 197
Joel Westberg Avatar answered Sep 23 '22 15:09

Joel Westberg