Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does array resizing invoke the GC?

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

like image 989
keyboardP Avatar asked Sep 02 '10 17:09

keyboardP


People also ask

What does array resize do?

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.

Which technique is applied to resize an array?

Resize(T[], Int32) Method is used to resize the number of elements present in the array. Or in other words, this method is used to change the number of elements of a one-dimensional array to the specified new size. It resizes the only 1-D array, not multidimensional array.

Can arrays be resized in C?

There is no way to resize an array. You can simply create a new array of size 2, then copy all the data from the previous one to the new one. realloc does it for you with dynamic memory.

Why can arrays be resized?

If the array were to be resized later on, that other information would have to be moved somewhere else in order for the array to get bigger. That's a lot of shuffling that we don't want to deal with, so computer architects disallow array resizing to make things simpler.


1 Answers

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.

like image 69
Jon Skeet Avatar answered Oct 14 '22 22:10

Jon Skeet