You should defer performance micro-optimizations until a point where you actually measure and observe a problem. That said...
Resizing arrays in .NET requires them to be reallocated. Memory in a .NET process is (generally) laid out without gaps - so you cannot resize something like an array without moving it to a new location in the heap.
You normally should not care about how Resize()
works internally - but in this case, the documentation actually explicitly describes what happens:
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.
Keep in mind that memory allocation in .NET is quite efficient - it mostly involves moving a high-water mark pointer up the address space of the heap and zeroing out the memory. Unless you are allocating an unusually large array, or doing so over and over in a tight loop you are not likely to run into issues.
There's really no better way to resize multi-dimensional data, in your case. However - you should strongly consider encapsulating this behavior in a custom class. It's not a good idea to pass around raw array objects - there are too many ways for things to go wrong. Especially, since when resized there is a new array instance - which could break any code that holds on to references to the old array instance and assumes they are still valid.
You can always create a class that provides indexer properties and has the syntactic "look-and-feel" of a multidimensional array, without actually exposing one. Unfortunately, to my knowledge there are no built-in multi-dimensional collection classes in the .NET class library. However, writing a simple wrapper should not be too hard.
By the way, if you are truly concerned about performance, you should be aware that .NET multdimensional arrays are know to perform significalty slower than one dimensional and even jagged arrays (double[][]
).