Noah Roth
Noah Roth

Reputation: 9220

Resizing array performance?

I'm wondering if constantly resizing byte arrays can take a big hit on performance. I'm adding data to a class and if the class already contains that data type I need to add it to the existing byte array, which means I'll need to resize it. The problem is that there are some data types that I have that will be adding in bulk which means there could be multiple array resizes occurring.

Would this make a huge impact on performance? This class CAN be very performance critical.

If it does, then I might have to do a design-overhaul.

Upvotes: 8

Views: 15102

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 160922

If resizing is required then you should use a List<byte> instead. Arrays cannot be resized so you would have to create a completely new array and then copy the old content into the new array before adding additional content (this is what Array.Resize does if that's what you were referring to).

List<T> is using an array internally but will optimize resizing so you don't have to deal with it.

Essentially once the internal array is full and new content is added, List<T> will double the internal array size, hence resizing should in fact occur very rarely - if you resize your array directly on the other hand you will either have to employ a similar strategy and keep a "size counter" or take the resize performance cost on any content addition.

Upvotes: 11

ziq
ziq

Reputation: 1018

Yes it is impacting performance. Resize array does not simply make the original array longer or shorter, it will create a new array and copy the data from old to new if necessary.

As suggested in the comment, use dynamic container such as List or ArrayList, while the latter is not type save but is convenient to use, which I prefer. You can take a look at : http://msdn.microsoft.com/en-us/library/system.collections.arraylist.aspx

Upvotes: 2

Related Questions