I was doing a lot of heavy indexer work in my program and noticed that accessing elements in an Array seemed a hell of a lot faster then accessing them in a List.
Anyway I wrote this little test program to time how long they take.
using System;
using Collections = System.Collections.Generic;
using Threading = System.Threading;
namespace Bob
{
public static class Application
{
[STAThread]
public static void Main( string[] ArgumentArray )
{
int Ticks = 0;
int[] Array = new int[320];
Collections.List<int> List = new Collections.List<int>();
for( int x = 0; x < Array.Length; x++ )
{
List.Add( x );
}
Threading.Thread.Sleep( 1000 );
Ticks = System.Environment.TickCount;
for( int i = 0; i < 5000000; i++ )
{
for( int j = 0; j < Array.Length; j++ )
{
Array[j] = j;
}
}
Console.WriteLine( "Array performance: {0}", System.Environment.TickCount - Ticks );
Threading.Thread.Sleep( 1000 );
Ticks = System.Environment.TickCount;
for( int i = 0; i < 5000000; i++ )
{
for( int j = 0; j < List.Count; j++ )
{
List[j] = j;
}
}
Console.WriteLine( "List performance: {0}", System.Environment.TickCount - Ticks );
Console.ReadLine();
return;
}
}
}
The results where 2620 for the Array and 13200 for the List. I was under the impression that the .Net 2.0 List class operated similar to a C++ std::vector and that there would be very little(or no) difference between accessing it and an array.
I wrote a simple class to mimic the C++ std::vector to see how it could perform.
public sealed class Vector<T>
{
private T[] Array = null;
public int Size
{
get
{
return SizeProperty;
}
private set
{
SizeProperty = value;
}
}
private int SizeProperty = 0;
public T this[int Index]
{
get
{
return Array[Index];
}
set
{
Array[Index] = value;
}
}
public Vector()
{
Array = new T[8];
return;
}
public Vector( int Reserved )
{
Array = new T[Reserved];
return;
}
public void Add( T Value )
{
Array[Size] = Value;
Size++;
if( Size >= Array.Length )
{
System.Array.Resize<T>( ref Array, Array.Length << 1 );
}
return;
}
public T[] ToArray()
{
if( Size == Array.Length )
{
return Array;
}
T[] NewArray = new T[Size];
System.Array.Copy( Array, NewArray, Size );
return NewArray;
}
}
Using the same style test as the program above, the result was exactly the same as the Arrays.
Can any of the .Net gurus explain how the List class works and why its indexer performance is so bad?
I did run the tests multiple times to make sure some other process wasn't hogging the CPU and messing it up and I got around the same results every time.
I'm on an Athlon64 at 2Ghz, maybe it was something to do with the way the JIT compiled it. Perhaps other people could run the test program and post their results.
Edit: Changed loop size from 10000000 to 5000000 to match other posts.
[Edited by - Scet on July 22, 2007 4:18:04 PM]