views:

134

answers:

4

Hi,

I looked into the implementation of Array.Resize() and noticed that a new array is created and returned. I'm aiming for zero memory allocation during gameplay and so I need to avoid creating any new reference types. Does resizing an array trigger the Garbage Collector on the previous array? I'm creating my own 2D array resizer, but it essentially functions in the same way as the .NET Resize() method.

If the new array is smaller than the previous one, but excess objects have already been placed back into a generic object pool, will this invoke the GC?

Arrays will constantly be created in my game loop, so I need to try and make it as efficient as possible. I'm trying to create an array pool as such, so that there's no need to keep creating them ingame. However, if the resize method does the same thing, then it makes little sense to not just instantiate a new array instead of having the pool.

Thanks for the help

+2  A: 

Yes, using Array.Resize causes a new array to be allocated and the old one to eventually be collected (unless there are still references to it somewhere).

A more low-level array resizer could possibly do some minor optimization in some cases (for example when the array is being made smaller or there happens to be memory available right after the array), but .NET's implementation doesn't do that.

Matti Virkkunen
A: 

Implicitly yes.

Explicitly no.

Andrew Lewis
+6  A: 

Array.Resize doesn't actually change the original array at all - anyone who still has a reference to it will be able to use it as before. Therefore there's no optimization possible. Frankly it's a badly named method, IMO :(

From the docs:

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.

So no, it's not going to reuse the original memory or anything like that. It's just creating a shallow copy with a different size.

Jon Skeet
That's a good point. It would have been better to accept the original by value and return the new one. The whole passing by reference here could really confuse a junior programmer in this case.
Brian Gideon
I was going through the method in Reflector and it just didn't sit right when I saw a new array being created. I guess I'm going to have to come to a compromise regarding the design, and carry out a few performance tests. Thanks for the reply!
keyboardP
A: 

Any allocation will eventually be cleaned up by the GC when no more references exist, so yes.

If you want to avoid resizing your arrays, the best thing you could do would be to preallocate with a large enough size to avoid having to reallocate at all. In that case, you might as well just use a collection class with an initial capacity specified in the constructor, such as List.

Zor