Deleting String[] in Java
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?
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.
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.
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.
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?
Have you considered using a LinkedList instead of a String[]?
精彩评论