Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to create variables (memory management)

You create a variable to store a value that you can refer to that variable in the future. I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

If I were to have a variable that I won't be referring to agaon, would removing the reference/value vars I'm using (and just using the numbers when needed) save memory? For example:

int number = 5;
public void method() {
    System.out.println(number);
}

Would that take more space than just plugging '5' into the println method?

I have a few integers that I don't refer to in my code ever again (game loop), but I've seen others use reference vars on things that really didn't need them. Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

like image 606
Vince Avatar asked Dec 31 '13 22:12

Vince


2 Answers

I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.

like image 55
Peter Lawrey Avatar answered Sep 20 '22 21:09

Peter Lawrey


In your example number is a primitive, so will be stored as a value.

If you want to use a reference then you should use one of the wrapper types (e.g. Integer)

like image 44
djhworld Avatar answered Sep 24 '22 21:09

djhworld