List <T> vs array perfomance
I am trying to set List <int> value
List< int > a;
//...
a[i] = X;
ilspy shows that the setup compiles to:
callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::set_Item(int32, !0)
But this code
int[] b;
//...
b[i] = Y;
compiles to
stelem.i4
And it was 7 times faster with my standard.
As I understand it, a virtual call is more expensive than a stele. Is it possible to use List <T> with perfomace array
Update
the code:
static void Main(string[] args)
{
int N = int.Parse(args[0]);
int M = int.Parse(args[1]);
var sw = new Stopwatch();
sw.Start();
int[] a = new int[N];
for (int k = 0; k < M; ++k)
{
for (int i = 0; i < N; ++i)
{
a[i] = i * 2;
a[i] -= i;
a[i] += 1;
}
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + ":" + a[N - 1]);
var b = new List<int>(N);
for (int i = 0; i < N; ++i)
{
b.Add(0);
}
sw.Restart();
for (int k = 0; k < M; ++k)
{
for (int i = 0; i < N; ++i)
{
b[i] = i * 2;
b[i] -= i;
b[i] += 1;
}
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds + ":" + b[N - 1]);
}
Launch and output:
> ./Console.exe 1000000 100
166:1000000
1467:1000000
+4