Arrays and IList<T>

3/10/2006 6:51:41 PM

Arrays and IList<T>

Rico recently posted a puzzle about Arrays and IList performance. I posted a comment on his blog on performance issues that I observed with generics support for arrays.

The runtime implements IList<T> for arrays (I believe) by mapping Array’s interface methods to generic methods in the internal SZArrayHelper class.

The IList<T> performance of array is not optimal because a costly cast operation occurs for each call to any of the methods with the interface. As a result, some of the nongeneric IList methods may actually perform better than the corresponding  generic methods, especially in those methods that do not involve any boxing.

What we gain from remove boxing with the generic IList<T>, we lose from extra cast operations. These cast operations are probably needed to support array covariance (at least through shared code). A string array, for instance, can be implicitly cast to an object array. Therefore, that string array needs to support both IList<object> and IList<string>.

Fortunately, unlike IList<T>, the more frequently used IEnumerable<T> interface for arrays has an optimal implementation.

There are some other caveats with using IList<T> for arrays. For instance, Collection<T>.IsReadOnly is true for arrays, the reason being that new items can’t be added or removed from the array.

Comments

 

Navigation

Categories

About

Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media