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

后端 未结 7 1586
遇见更好的自我
遇见更好的自我 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 19:22

    I found on high volume function calls for larger value types that passing by ref was quicker, slightly. If you have a high volume of function calls and need speed this might be a consideration. I'm open to alternative evidence.

    public static void PassValue(decimal value)
    {
    
    }
    
    public static void PassRef(ref decimal value)
    {
    
    }            
    
    decimal passMe = 0.00010209230982047828903749827394729385792342352345m;
    
    for (int x = 0; x < 20; x++)
    {
        DateTime start = DateTime.UtcNow;
        TimeSpan taken = new TimeSpan();
    
        for (int i = 0; i < 50000000; i++)
        {
            PassValue(passMe);
        }
    
        taken = (DateTime.UtcNow - start);
        Console.WriteLine("Value : " + taken.TotalMilliseconds);
    
        start = DateTime.UtcNow;
    
        for (int i = 0; i < 50000000; i++)
        {
            PassRef(ref passMe);
        }
    
        taken = (DateTime.UtcNow - start);
        Console.WriteLine("Ref : " + taken.TotalMilliseconds);
    }
    

    Results:

    Value : 150
    Ref : 140
    Value : 150
    Ref : 143
    Value : 151
    Ref : 143
    Value : 152
    Ref : 144
    Value : 152
    Ref : 143
    Value : 154
    Ref : 144
    Value : 152
    Ref : 143
    Value : 154
    Ref : 143
    Value : 157
    Ref : 143
    Value : 153
    Ref : 144
    Value : 154
    Ref : 147
    Value : 153
    Ref : 144
    Value : 153
    Ref : 144
    Value : 153
    Ref : 146
    Value : 152
    Ref : 144
    Value : 153
    Ref : 143
    Value : 153
    Ref : 143
    Value : 153
    Ref : 144
    Value : 153
    Ref : 144
    Value : 152
    Ref : 143
    
    0 讨论(0)
提交回复
热议问题