Performance of pass by value vs. pass by reference in C# .NET

后端 未结 7 1585
遇见更好的自我
遇见更好的自我 2020-12-05 18:27

I\'ve created a lightweight class with a constructor that takes around 10 parameters. The class does not change the parameter values; it just stores the values locally via

相关标签:
7条回答
  • 2020-12-05 18:59

    Only use ref if the method needs to alter the parameters, and these changes need to be passed onto the calling code. You should only optimize this if you have run it through a profiler and determined that the bottleneck is indeed the CLR copying the method parameters onto the stack.

    Bear in mind the CLR is heavily optimized for calling methods with parameters, so I shouldn't think this would be the issue.

    0 讨论(0)
  • 2020-12-05 19:08

    As far as I understand you have a class with only fields and a constructor that is assigning the parameters to those fields, right?

    If that is the case I would consider using ref in the constructor bad practice. If you assign the parameter to a field in that class it is stored by value in any case. So if you dont change the value in the constructor there is no need to use it by reference.

    0 讨论(0)
  • 2020-12-05 19:10

    No. Passing parameters by reference adds overhead, so it would only decrease the performance.

    0 讨论(0)
  • 2020-12-05 19:17

    If the class is only holding parameters maybe you should use a struct?

    Maybe this is of interest?

    When to use struct?

    0 讨论(0)
  • 2020-12-05 19:19

    I am not sure for c#, however for c++/c it depends on what you are passing. If you are passing a base type (int, float, double, char).... then passing by value is faster then passing by reference (because function call are optimized for this. If you are passing something larger, a large class, an array, long string... then passing by reference is much, much faster because if you are doing an int[100000] then the processor will have to allocate a 100000 x 32/64 (depending on architecture) chunk, and then copy all of the values over, that takes a lot of time. Whereas by reference just passes a pointer

    C# abstracts most of this away, so I do not know what it does, but I think that what applies to c++/c in terms of efficiency can usually apply to c#.

    0 讨论(0)
  • 2020-12-05 19:20

    No. For reference types, you are passing a reference already, there is no need to pass the reference by reference unless you want to change what the reference points to, e.g. assign it a new object. For value types, you can pass by reference, but unless you have a performance problem, I wouldn't do this. Especially if the types in question are small (4 bytes or less), there is little or no performance gain, possibly even a penalty.

    0 讨论(0)
提交回复
热议问题