user3527825
user3527825

Reputation: 55

Does creating an instance variable that is set to be a new object inside a method save memory over creating a local variable inside the method?

I think this question is a bit confusing without looking at any code, so here is my example:

This:

public class Example {

    public Object foo() {
        return new Object();
    }
}

vs this:

public class Example {

    private Object object;

    public Object foo() {
        object = new Object();
        return object;
    }
}

Does the 2nd example just switch the memory address of the instance variable and not create a new one? Does doing it the 2nd way save memory?

The reason I ask is because the method could very likely be called very many times during the runtime of the program.

Thanks!

Upvotes: 2

Views: 64

Answers (4)

mstrthealias
mstrthealias

Reputation: 2921

Does the 2nd example just switch the memory address of the instance variable and not create a new one? Does doing it the 2nd way save memory?

No, the new instance will be created in a new location in memory.

The existing memory will not be available until garbage collection has determined there are no references to the existing instance.

Upvotes: 2

Christian MICHON
Christian MICHON

Reputation: 2160

I suggest you to use jvisualvm or jmc to check both codes.

Run each code with decent and similar scenario. Both tool I mentioned will report memory consumption and garbage collection.

Upvotes: 1

Smith_61
Smith_61

Reputation: 2088

The second example actually uses more memory than the first example because now each instance of Example must be big enough to store a reference to an Object. I believe you meant to write

public class Example {
    public Object obj = new Object();
    public Object foo() {
        return obj;
    }
}

Now this example has the same memory requirement, but this does have the added benefit of not reallocating an Object every time foo is called. Which will save memory if you call foo() repeatedly.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201399

Does it save memory? No, it uses more memory. Because now every instance of Example has an inaccessible field Object. And calling get on it replaces the current local value with a new value before returning the new reference. Meaning the old reference is irrelevant.

Upvotes: 1

Related Questions