开发者

What's best for array reinitialization : set to null by iteration or simply allocate a new array?

In my code, I have an array that has about 1000 elements :

Object[] arr = new Object[1000];

After my array is populated (the whole array or just partially), I need to reinitialize it. From what I know, I have two choices : to initialize it by new keyword, or to iterate over it and set each element to null. I think firs开发者_如何学Ct approach is best than second, but also I'm waiting for your thoughts.

Any links or articles on this topic are welcome.

Thanks in advance


First one is better. By reinitializing it with new keyword, you put the previous set of array eligible for garbage collection by providing a path to GC (assuming that other live objects does not have a reference to any of them).

The second one would achieve the same effect eventually, but there is an added performance hit because you need to iterate one by one. For 1000 records, this would likely happen very fast, but if the number grows then the hit would be greater.


Agree with your first choice use arr = new Object[1000] and don't loop it.

Also the use of new Object[1000] doesn't create 1000 objects it only makes a "placeholder" for 1000 objects so it's a very cheap operation.

And if you know you will populate all 1000 objects you can just use the array as is without reinitializing it.


First is the best way Object[] arr = new Object[1000]; also you can find in below link, number of ways array can be initialised

array initialisation


First by setting the array to null you effectively tell the GC it can check everything in that array and clean it up if necessary. So there is no need to iterate through the elements, even if you arent going to do a new right away.

That being said, the only time you really would ever explicitly need to set a variable(for GC purposes anyway) to be explicitly NULL is if you no longer need the data pointed to by that variable, but have nothing new to put in its place AND the variable, for whatever reason, will stay in scope for a while. In that case its advisable to set the value to null, or better yet, re-work your code so that variable goes out of scope and that is done for you.

So for instance, in your example say arr was a static member of some class and you just needed to do some processing on the array at startup and never look at it again. In that case, the contents of arr will stick around for the entire time your program is running UNLESS you explicitly set it to null(or assign it a new value).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜