Category nameļ¼šConversion

In search for the fastest IList to IList<T> conversion

I was yet again busy with a generic data layer. I like type safety as it provides compile time safety instead of run-time. The current released Db4o build (6.1) does not support type safe result list thus I had a need to convert these. My first approach was to just do a foreach like the following example:

Conversion one 

        public static System.Collections.Generic.IList<T> Convert1<T>(
            System.Collections.IList source
            System.Collections.Generic.IList<T> result = new System.Collections.Generic.List<T>(source.Count);
            foreach (T o in source)
            return result;

But after I had this working I thought that this could be slow and that another solution was probably faster. I did a quick google search and ended up at a post of Bil Simser. There I saw some approaches in the comments but without additional information about its performance. So I made a little performance test where I tested not only the first example but also two others:

Conversion two 

        public static System.Collections.Generic.IList<T> Convert2<T>(
            System.Collections.IList source
            System.Collections.ArrayList list = new System.Collections.ArrayList(source);
            return new List<T>(list.ToArray(typeof(T)) as T[]);

Conversion three 

        public static System.Collections.Generic.IList<T> Convert3<T>(
            System.Collections.IList source
            T[] output = new T[source.Count];
            source.CopyTo(output, 0);
            return output;

After creating an ArrayList I initialized it with 20.000.000 instances of my test class and then converted it to a type-safe IList<T>. After running it several times with no load on my system I got the following results:

Conversion one : ~2175ms
Conversion two : ~ 884ms
Conversion three : ~133ms

So my “vingerspitsgevoel” was right again! What amazes me is that the conversions timings are so far apart. At first I didn’t think that the second conversion would differ that much compared with the first but I think the .ToArray(..) method has CLR optimizations just as .CopyTo(..) method in the third example. The third conversion is more then 16 times faster then the first and even more then 6,5 times faster then the second.

The third conversion is even faster with much smaller arrays and lists (200.000 items). Then it is ~26 times faster then the first and ~7 times faster then the second conversion. I did this test on a Intel 3GHz D processor with 2GB of RAM on Windows XP Pro with the .net 2.0 framework.

So if you were searching for (probably the fastest) ArrayList / IList to IList<T> conversion then you have found it. I immediately added the third conversion method to my personal framework code and I suggest that you do to after seeing these results.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta