I am working on an Android app and a method I am writing might get called a bunch of times. In this method I am making updates to the user interface. Memory use and performance are important to me. The way I see it, I have 2 options for making the UI changes.
The first is to makes new objects every time. That is to say something like:
public void myMethod(){
new View().makeVisible();
}
The second is to declare the object as a variable globally and reference it in the method. This might look like:
View myView = new View();
public void myMethod(){
myView.makeVisible();
}
Obviously the if this method only called a few times any difference is going to be small. However if I am potentially calling this many times, and there are many variables being call/or created this way, does the second way increase performance?
As the other answers have indicated, reusing the same object instead of repeatedly instantiating a new one for every method call will reduce your memory footprint and improve performance with respect to garbage collection.
But I would actually think about maintainability first. Is reusing the same object going to make your code much more complicated (and potentially introduce bugs)? It’s good to keep efficiency in mind as you program, but avoid premature optimization that complicates your project and slows development.
If performance and memory usage are a concern, then yes it will benefit you to reuse the same
View:If you really want to get resource minded, you could even lazy-load the object – that is, create it only as soon as it’s needed. However I would recommend using Guava’s
Suppliers.memoize(Supplier)to take care of this instead of hand-coding that behavior:That’s probably extreme for this particular situation though.