Passing Values by Reference vs. by Value (Speed Differences?)

  • Thread starter Thread starter Joe Keller
  • Start date Start date
J

Joe Keller

Hello,

In C++, it was always faster and "cheaper" to pass values by reference vs.
by value. Does the same line of thinking hold true with C# in the .NET CF?

For example, assume I have a procedure "Foo" in my application and that
"Foo" requires a parameter "X". In addition, assume that "Foo(X)" is called
quite heavily within the application.

Is it faster and "cheaper" to call "Foo(X)" by passing "X" by reference or
by passing "X" by value?

By Reference:
private void Foo(ref X);

By Value:
private void Foo(X);

Thanks,

Joe
 
Passing by ref passes a pointer and doesn't require copying the data to the
stack, so it should be faster (I've not empirically tested it) and use less
resources.

-Chris
 
Keep in mind also that reference types are not required to be passed by
reference sinse they always passed by ref.
 
And that it's *not* true that passing by reference is "always faster".
Passing by reference requires that a four-byte value be pushed onto the
stack, so any parameter that can be pushed faster by value (an integer
value, for example), will be handled more quickly by value than by reference
(and the code to access the parameter is quicker, also, because it doesn't
have to dereference a pointer to get to the value).

Paul T.
 
Back
Top