I have String[] inputMsg declared outside a loop and inside a loop I have
inputMsg = new String[someSize];
Since the loop can loop lots of times, I find it out that creating new String[someSize] everytime realy wasteful so in the of each iteration of the loop I would like to remove that memory allocation or to delete it's content so the inputMsg will be null.
How can it be done in Java?
-
creating an array of anything is going to have minimal impact on the amuont of memory allocated. Unless your array is 1000's long, it would be silly to worry about.MeBigFatGuy– MeBigFatGuy2011-10-01 20:00:46 +00:00Commented Oct 1, 2011 at 20:00
5 Answers
Why declare it outside a loop?
for (...) {
String[] inputMsg = new String[someSize];
...more code...
}
The GC will take care of freeing the memory. If the GC turns out to be a bottleneck, and you have the numbers to prove it, then we can talk some more. But, it turns out most GCs are fairly efficient at reclaiming short-lived objects.
2 Comments
You don't delete objects in Java, you remove the references to them and wait for the garbage collector to collect them.
If you have a String[] (ie, an array of String) you can attempt to reuse it (especially if the old and new arrays are the same size), but that the best you're going to do.
If you want to be able to add things to an array (change its size) over time you shouldn't use a regular [] type array but should use a Vector or one of the other collection objects.
2 Comments
You can't delete anything in java by hand. This is automatically done by the garbage collector. It runs from time to time or if more memory is needed. You can't influence it.
2 Comments
You should be able to force a garbage collect with System.gc() or Runtime.gc(). However, I strongly advise against it. Why do you want the memory freed quickly? Is there a specific reason?
3 Comments
System.gc() cannot force garbage collection, it can only suggest it.