I just wanted to know what happens behind my program when I declare and initialize a variable and later initialize it again with other values, e.g. an ArrayList or something similar.
What happens in my RAM, when I say e.g. this:
ArrayList<String> al = new ArrayList<String>();
...add values, work with it and so on....
al = new ArrayList<String>();
So is my first ArrayList held in RAM or will the second ArrayList be stored on the same position where the first one has been before? Or will it just change the reference of “al”?
If it is not replaced…is there a way to manually free the RAM which was occupied by the first arraylist? (without waiting for the garbage collector)
Would it help to set it first =null?
Nice greetings,
poeschlorn
The code you post will allocate a new ArrayList instance. If you want to reuse the same one, you can do this:
But do this with caution – if you pass the initial instance of
a1to other code that will be using it for a longer period, then clearing it will cause problems and you will need a separate instance.But also note that the savings you get from recycling object arrays and ArrayLists aren’t that great. If you were storing 10 x 4096 byte strings in the ArrayList, the array list itself only occupies space proportional to the size of the references, e.g. circa 4 bytes x 10 = 40 bytes. This is a simplification, but the principle is correct. So, even if you reuse the same array list, you are only saving yourself the memory used to store the object references, not the objects themselves. With that in mind, and the risks of causing bugs by modifying a collection unintentionally, I would guess most people don’t bother recycling lists.
The memory management in a modern VM is really very good, and you should only start introducing memory “optimizations” when you see that there is a need for it. In fact, using objects for longer than their natural lifetime can have a negative effect on garbage collection performance.
My advice is, code it clearly first, profile, and only focus on optimizing memory use when you see there is a problem and have identified the cause.
Good luck!