Recently, I started working on a project where many reference parameters are passed around by reference. I’ve looked into a lot of the code and the majority of these methods could lose the ref parameter. Although the code functions fine, I was wondering what kind of performance hit there might be by double dereferencing every argument rather than just passing the reference by value.
For example, this code:
public void EmptyList(ref List<string> test)
{
test.Clear();
}
VS this:
public void EmptyList(List<string> test)
{
test.Clear();
}
EDIT
After reading what Nicholas Carey had to say, I tried the same thing with the code above. This was the resulting assembly:
EmptyList(ref List<string> test)
00000028 mov eax,dword ptr [ebp-40h]
0000002b mov ecx,dword ptr [eax]
0000002d cmp dword ptr [ecx],ecx
0000002f call 719210C4
EmptyList(List<string> test)
00000028 mov ecx,dword ptr [ebp-40h]
0000002b cmp dword ptr [ecx],ecx
0000002d call 71920FD4
The difference calling by explicit reference and calling by implicit reference is the difference between the
lea(Load Effective Address) instruction and themov(‘Move’) instruction.AFAIK, on any modern processor, both of these instructions, in the form used, execute in a single clock cycle, so the difference is pretty much moot.
Here’s the code generated (debug mode) for the call by [explicit] reference:
And here’s the code generated (debug mode) for the call by [implicit] reference:
The code generated for the called method/function is identical in either case.
Here’s the sample code I used, FWIW:
IMHO, omit the
refkeyword unless it’s actually needed: all it really does is add semantic noise to the equation.