Performance of pass by value vs. pass by reference in C# .NET

Only use ref if the method needs to alter the parameters, and these changes need to be passed onto the calling code. You should only optimize this if you have run it through a profiler and determined that the bottleneck is indeed the CLR copying the method parameters onto the stack.

Bear in mind the CLR is heavily optimized for calling methods with parameters, so I shouldn't think this would be the issue.


No. For reference types, you are passing a reference already, there is no need to pass the reference by reference unless you want to change what the reference points to, e.g. assign it a new object. For value types, you can pass by reference, but unless you have a performance problem, I wouldn't do this. Especially if the types in question are small (4 bytes or less), there is little or no performance gain, possibly even a penalty.


I found on high volume function calls for larger value types that passing by ref was quicker, slightly. If you have a high volume of function calls and need speed this might be a consideration. I'm open to alternative evidence.

public static void PassValue(decimal value)
{

}

public static void PassRef(ref decimal value)
{

}            

decimal passMe = 0.00010209230982047828903749827394729385792342352345m;

for (int x = 0; x < 20; x++)
{
    DateTime start = DateTime.UtcNow;
    TimeSpan taken = new TimeSpan();

    for (int i = 0; i < 50000000; i++)
    {
        PassValue(passMe);
    }

    taken = (DateTime.UtcNow - start);
    Console.WriteLine("Value : " + taken.TotalMilliseconds);

    start = DateTime.UtcNow;

    for (int i = 0; i < 50000000; i++)
    {
        PassRef(ref passMe);
    }

    taken = (DateTime.UtcNow - start);
    Console.WriteLine("Ref : " + taken.TotalMilliseconds);
}

Results:

Value : 150
Ref : 140
Value : 150
Ref : 143
Value : 151
Ref : 143
Value : 152
Ref : 144
Value : 152
Ref : 143
Value : 154
Ref : 144
Value : 152
Ref : 143
Value : 154
Ref : 143
Value : 157
Ref : 143
Value : 153
Ref : 144
Value : 154
Ref : 147
Value : 153
Ref : 144
Value : 153
Ref : 144
Value : 153
Ref : 146
Value : 152
Ref : 144
Value : 153
Ref : 143
Value : 153
Ref : 143
Value : 153
Ref : 144
Value : 153
Ref : 144
Value : 152
Ref : 143

Tags:

C#