Java Variables & # 8594; replace? Optimizing memory
I just wanted to know what is going on behind my program when I declare and initialize a variable and then re-initialize it with other values, for example. ArrayList or something similar.
What happens in my RAM when I say eg. this is:
ArrayList<String> al = new ArrayList<String>();
...add values, work with it and so on....
al = new ArrayList<String>();
So my first ArrayList is stored in RAM or will the second ArrayList be stored at the same position as the first one? Or will he just change the "al" link?
If not replaced ... is there a way to manually free the RAM occupied by the first arraylist? (without waiting for garbage collection) Would it help to set = null first?
Good cheers, poeschlorn
a source to share
In the code you are posting, a new ArrayList instance will be allocated. If you want to reuse the same, you can do this:
ArrayList<String> al = new ArrayList<String>();
...add values, work with it and so on....
al.clear();
// now you can use a1
But do this with care - if you pass the original instance a1
to other code that will use it for a longer period, then cleaning it up will cause problems and you will need a separate instance.
But also note that the savings from recycling Arrays of Objects and ArrayLists are not huge. If you store 10 x 4096 byte strings in an ArrayList, the list of arrays itself takes up space proportional to the size of the references, for example. about 4 bytes x 10 = 40 bytes. This is a simplification, but the principle is correct. This way, even if you reuse the same list of arrays, you only save the memory used to store object references, not the objects themselves. With this in mind, and the risks of causing errors by modifying the collection unintentionally, I would assume that most people don't bother with recycling lists.
Memory management in a modern virtual machine is really very good, and you should only start implementing memory "optimizations" when you see it is necessary. In fact, using objects longer than their natural lifetime can negatively impact garbage collection performance.
My advice: first clearly articulate it, a profile, and only focus on optimizing memory usage when you see that there is a problem and have identified the cause.
Good luck!
a source to share
The new ArrayList will be allocated from some other part of memory, the reference will be changed to point to it, and if the old ArrayList is no longer mentioned by some other, this will be garbage collected. There is no way to manually free memory in Java. This happens automatically.
Parameters of variables to null have no value when afterwards it is set to something else or a local variable that goes out of scope anyway soon (but inside data structures like ArrayList, setting the elements of the contained array to null when the item is removed is required to avoid memory leaks).
a source to share