Value vs Reference: A Performance Test
I have recently started to learned about classes and objects in C♯. In one of my lectures, Rob Miles mentioned that passing by reference introduced a slight performance hit, and I decided to test this.
Here is the code I used:
using System;
using System.Diagnostics;
class ValueVsReference
{
public static void SetValue(int somenumber, int maxi)
{
for (int i = 0; i < maxi; i++)
{
somenumber = i;
}
}
public static void SetReference(ref int somenumber, int maxi)
{
for(int i = 0; i < maxi; i++)
{
somenumber = i;
}
}
public static void Main()
{
int iterations = 100000;
int a = 0;
Console.Write("Iterations: {0} ", iterations);
Console.Write("Value: ");
Stopwatch valuetime = new Stopwatch();
valuetime.Start();
SetValue(a, iterations);
valuetime.Stop();
Console.Write("{0} ", valuetime.Elapsed);
Console.Write("Reference: ");
Stopwatch referencetime = new Stopwatch();
referencetime.Start();
SetReference(ref a, iterations);
referencetime.Stop();
Console.WriteLine(referencetime.Elapsed);
}
}
(gist: https://gist.github.com/sbrl/b10bf5c765630562431f)
The results for 10,000 iterations can be found in this pastebin.
Average times:
- Value: 0.0000885
- Reference: 0.00009295
Final result: References are indeed slower than values, by ~5% (100 - ((0.00009295/0.0000885)*100)
). Normally you would not need to worry about this performance drop though since it is so small.