tags:

views:

75

answers:

3

Possible Duplicates:
Pass by value vs Pass by reference performance C#.net
Which is faster? ByVal or ByRef?

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?

+3  A: 

Take a look at this thread:

http://stackoverflow.com/questions/408101/which-is-faster-byval-or-byref

Hopes it will answer your question

MUG4N
+1  A: 

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.

Guffa
A small nitpick: If you have a *large* struct then passing it by ref might improve performance very slightly. Having said that, if your struct is so large that passing it by val noticeably impacts performance then you should seriously think about refactoring the type itself, and *not* about passing it around by ref.
LukeH
+1  A: 

There are value types and reference types in C#

In 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 that passing references to those references is faster than passing the references in the first place. It doesn't make sense.

In 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, you are concerned of the efficiency of passing it to functions, most probably you made a mistake making it a value type.

Maciej Hehl