Possible Duplicates:
Pass by value vs Pass by reference performance C#.net
Did anyone already test if passing parameters by reference is significantly faster than just copying them?
But the main focus of the question is: Are there any disadvantages using the ref keyword as opposite to not using it?
No, it doesn't improve speed significantly, or anything at all. On the contrary, by using the ref
keyword you are adding another level of indirection that only can make the code slower.
Parameters are normally passed by value, which means that they are copied. For simple values like int
, it simply means that a copy of the value is placed on the stack.
For reference types like a string
it means that a copy of the reference is placed on the stack. So, it doesn't mean that the entire object is copied, it's just the reference to the object that is copied.
You should generally not use the ref
or out
keywords, unless there is a special reason to do so.
There are value types and reference types in C#
In the case of reference types, passing them without the ref
keyword means passing references. I didn't test it, but I would expect that implementers of the compiler and the .NET framework made passing them as fast as possible. I can't imagine that passing references to those references is faster than passing the references in the first place. It doesn't make sense.
In the case of value types, it's another story. If a struct is big, copying it is costly for sure, and passing a reference should be faster. But value types are meant to be value types for a reason. If you have a value type and you are concerned about the efficiency of passing it to functions, most probably you made a mistake making it a value type.