Re: Array vs List<>

Sébastien Lorion <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.advanced
Message-ID <[email protected]>
First, a good thing to do is to estimate the final length of the list if
possible and set it in the constructor (allowing yourself for a slight error
margin). This will save you many resize/copy while populating the list. You
can also set the Capacity property at the end to remove the extra space
(which can be quite large depending on scenario), but at the cost of copying
the elements. Then, to make sure the list is read-only (but not its
elements), you can wrap it in a ReadOnlyCollection<T> or something similar.
Arrays are fine, as long as you don't expose them to the outside, ie you
have full control over the code that use them.

Sébastien
On Sat, Nov 1, 2008 at 9:00 AM, Simon Robinson <[email protected]>wrote:

> Very minor issue that occurred to me.
>
> The project I'm working on seems to have quite a few lists of objects,
> where each list is read in from a file when the application starts, and is
> subsequently guaranteed never to change; the data will be accessed
> constantly but neither the list nor the values of the objects in it will
> ever be modified.
>
> Because I don't know how many elements are going to be in the list until
> I've read them in, I tend to read them into a List<>, so I can dynamically
> expand it as I'm reading the elements in. However, because the list is then
> unchanged, there's no reason for it to be a dynamically expandable list. If
> it wasn't for the initialization process I'd just store them in a
> fixed-length array.
>
> So I'm curious, what are people's thoughts on keeping the data permanently
> in a list<>, or discarding the list<> and copying to an array as soon as the
> data is read in? An array entails the extra copy operation, but may lead to
> slightly clearer code. I'm guessing for subsequent read access, there's no
> performance difference. Any other factors I've missed?
>
> I realise this is most likely a pretty academic point that would have very
> little impact on the app either way, but I was curious...
>
> ===================================
> View archives and manage your subscription(s) at
> http://peach.ease.lsoft.com/archives
>

===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.