So I'm currently working on a program that needs to be able to deal with a large amount of data stored in arrays and it needs a method to clear out everything in the array. For the below example, would this be a bad thing to do memory wise? I know the garbage collector would eventually clean it up for you but is there a reason why another method (e.g. a for loop and setting each value within to null) might be better than this?
Object[] objArray = new Object[n];
/*Do some stuff with objArray*/
objArray = new Object[n]
Otherwise, doing this will allow this operation to run in O(1) time vs a for loop which would take O(n).
What you are doing when you are making an assignment is changing the value of the reference which that variable is holding to another value of another reference. The memory locations which the two arrays hold are still different even after assignment, you are just keeping in your variable another address.
Array in java can be copied to another array using the following ways. Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements.
Use List. clear() method to empty an array.
It is bad practice.
Firstly, assigning a new array to the variable doesn’t actually “clear” anything out (more on this below).
This is best practice:
objArray = null;
which makes the original array unreachable and therefore it will be (eventually) garbage collected.
It also avoids an unnecessary allocation of memory creating the empty array you used to replace the old one.
However, neither option “clears” out the original array, which may pose an, albeit small, security exposure. Until garbage collected, the contents of the array may be divinable if the memory contents are dumped etc.
The truly clear the array:
Arrays.fill(objArray, null);
No, it is not bad practice. However, nulling all indices of the array will very likely be faster (technically, this is what is called an implementation detail; but feel free to benchmark this on your specific system), because the extra step of allocating new memory is not needed. However, be advised to not fall victim to what is known as premature optimization, as it can cause you to waste time if you later find you need to make large changes. Also, mind that since you will keep using the existing array object, any other parts of your code that reference it will then also see the changes to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With