Is it generally more efficient to pass by ref?

Just a random thought, but, since passing by value means a creating a copy of the variable, I'm assuming that passing by reference is more efficient in processor terms.

Hence should one always pass by ref when given the choice (eg. when the method being passed the parameter doesn't modify it), or is the performance benefit (presumably pitifully insignificant for most simple variables) negated by the reduced readability ("why have they used refs everywhere !").

Thanks!

Carlos


PS sorry if this is a hopelessly newbesque question...



Answer this question

Is it generally more efficient to pass by ref?

  • AMJZA

    It's not that simple. It's true that passing by ref copies the value or reference in the case of an object, but you have to consider that passing by value requires that that argument only moves in one direction - i.e., it doesn't have to be marshalled back to the callee.

    But, it's unlikely that you should base whether to pass by ref or value on performance. It should be based on whether you need to use ref parameters or not.

    David Anton
    www.tangiblesoftwaresolutions.com
    Instant C#: VB to C# converter
    Instant VB: C# to VB converter
    Instant C++: C# to C++ converter and VB to C++ converter
    Instant J#: VB to J# converter
    Clear VB: Cleans up VB.NET code
    Clear C#: Cleans up C# code



  • PamelaS

    When you have a reference type (i.e. class instead of struct), the variable for that object is actually a pointer, so the entire object is not being copied around, just the pointer.

    Thus, a 200 character string being passed into a method like:

    public void Test(string str);

    results in a 4 byte pointer being passed in (8-byte if it's running in 64-bit). When you're passing a reference type with the ref keyword, it's the pointer that is being passed by reference (in C++ terms this would be like CCustomer **myValue instead of CCustomer *myValue).

    Value types (structs) work as you have assumed in your post. Have a look at http://www.yoda.arachsys.com/csharp/parameters.html for a much better exposition than mine.



  • er824

    Thanks kids, much appreciated.



  • Is it generally more efficient to pass by ref?