blah blah blah is here! blah blah » Close

up2down
link

I find that I practically never use arrays anymore because of the potential waste of memory from having to declare arrays more than large enough. Another reason is because arrays look old fashioned to me. List<> seems to have largely eliminated arrays for me.

Also System.String also seems to have eliminated the need for arrays of char.

This has gotten to the point I'm not even sure what the correct array declaration and indexing syntax is anymore. (Experience: many projects in C, only a couple in C++, and a few in C#, spread over 20 years).

I would appreciate comments, insights or links to articles that may give some idea what the speed performance penalty is in avoiding arrays. Likewise, if style guidelines have anything to say about my design choice with respect to the use or lack of use of arrays. Also I'd be interested in what your experiences have been with the performance of jagged arrays?

Regards,
Brian

last answered 2 years ago

1 answers

link

There's no doubt that the fastest collection type in .NET is the single dimensional array, because Microsoft spent a lot of time optimimizing it when .NET and the CLR were first designed. As you know, the length of an array object cannot be changed once it's been created.

Generic types came along a new years later and List<T> is only marginally slower than an array of T. As you know, a List<T> can increase its capacity as new elements are added and actually uses a private array field as its backing store. This array needs to be recreated and the original elements copied over when the List needs additional capacity, which is why it's slightly slower.

If I remember correctly, the internal array starts off with a length of 4, when the first element is added to the list. When the fifth element is aded, the internal array is doubled in size to 8 and so on. So, as you'll see, memory is still, in a sense, 'wasted' even with a List but, if you didn't do this, performance would be poor.

Although there's a close relationship between character arrays and strings (it's easy to convert one to another), the latter doesn't actually use the former as a backing store. Although the length of a character array cannot be changed, its elements can be whereas a string is completely immutable.

I don't think whether you prefer Lists to arrays or strings to character arrays is a matter of style - you should really just use the best one for the job in hand :)

Jagged arrays are just arrays of arrays. They're more versatile than rectangular arrays, IMO, though initializing them is not very intuitive. I've always found performance to be quite good though, once you're 'sure' the code won't throw any exceptions, you can improve it significantly by using pointers in unsafe code to circumvent array bounds checking on every element access which, although much safer, is a drain on performance compared to C/C++.

Feedback