Java: Do global variables save memory and / or time?

I am working on an Android application, and the method I am writing can be called a bunch of times. In this method, I am making updates to the user interface. Memory and performance are important to me. As I see it, I have 2 options for changing the user interface.

The first is to create 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 refer to it in the method. It might look like this:

View myView = new View();

public void myMethod(){
myView.makeVisible();
}

Obviously, if this method is called only a few times, any difference will be small. However, if I potentially call it many times, and there are many variables called / created in this way, does the second way increase performance?

+5
4

, .

. , (, , )? , , , .

, , View:

final View myView = new View(); //made final because it shouldn't be reassigned

, , .. . Guava Suppliers.memoize(Supplier), :

final Supplier<View> myViewSupplier = Suppliers.memoize(new Supplier<View>() {
    @Override
    public View get() {
        return new View();
    }
});

...

public void myMethod() {
    View myView = myViewSupplier.get(); //lazy-loads when first called
    myView.makeVisible();
}

, , .

+2

, - , , . : " , View?".

- , . OO, .

, , - , "View" /. , , factory - , "myMethod" - factory, .

"" - , . .

, - . , . , .

+1

.

, , , . .

: , .

0

, , , , , . , , , . , , , , , , .

Another incentive to reuse the same object is that the implementation of the Java virtual machine is different from using the garbage collection in that when the variable goes out of the area to which it is inaccessible - when the freed memory corresponding to the JVM is not always the same thing. You could find this with an alternative, you have instances where many species are sequentially allocated, but not all are freed until the process is idle for a while, actually making the application memory hog exactly the way you DO NOT want.

0
source

All Articles