Do you save the garbage collector work by declaring in-method variables as attributes?

java, memory, performance

Solution

Local variables are allocated on the stack.

In this case

public int addToA(int a) {
    int b = a + 2;
    return b;
}

when the method returns, and the stack frame containing `b` is popped, the memory it was taking will be recovered automatically. The Garbage Collector is not involved.

In this case

public class Core {

    int b;

    public int addToA(int a) {
        b = a + 2;
        return b;
    }
}

`b` will be allocated in the heap space reserved for the `Core` object. It will only be garbage collected when `Core` is collected.

Assuming that the addToA method is called a lot do you save the garbage collector work (and speed up your program) by using the second one?

As far as I know, you won't gain anything.

Go read T.J. Crowder's Community Wiki post for an example on when to and when not to do what you are proposing.

Problem

Compare ``` public class Core { public int addToA(int a) { int b = a + 2; return b; } } ``` To ``` public class Core { int b; public int addToA(int a) { b = a + 2; return b; } } ``` Assuming that the `addToA` method is called a lot do you save the garbage collector work (and speed up your program) by using the second one?

Original source