Consider this simple benchmark of readonly and const ints. We try to determine if there is any performance benefit to using readonly (or avoiding it).
using System;
using System.Diagnostics;
class Test
{
readonly int _value1;
int _value2 = 1;
const int _value3 = 1;
public Test()
{
_value1 = int.Parse(
"1");
}
public int GetValue1()
{
return _value1;
}
public int GetValue2()
{
return _value2;
}
public int GetValue3()
{
return _value3;
}
}
class Program
{
static void Main()
{
Test test = new Test();
const int m = 1000000000;
Stopwatch s1 = Stopwatch.StartNew();
// Version 1: access readonly.
for (int i = 0; i < m; i++)
{
if (test.GetValue1() != 1)
{
throw new Exception();
}
}
s1.Stop();
Stopwatch s2 = Stopwatch.StartNew();
// Version 2: access field.
for (int i = 0; i < m; i++)
{
if (test.GetValue2() != 1)
{
throw new Exception();
}
}
s2.Stop();
Stopwatch s3 = Stopwatch.StartNew();
// Version 3: access const.
for (int i = 0; i < m; i++)
{
if (test.GetValue3() != 1)
{
throw new Exception();
}
}
s3.Stop();
// Results.
Console.WriteLine(s1.ElapsedMilliseconds);
Console.WriteLine(s2.ElapsedMilliseconds);
Console.WriteLine(s3.ElapsedMilliseconds);
}
}
562 ms readonly
300 ms int
555 ms const