locked
C# compiler and performance with setting a method to a variable RRS feed

  • Question

  • User-1188570427 posted

    Is there a performance hit if you set your return method to a variable instead of just using the method?

    FIRST:

    var number= GetValueNbr();
    
    number = number++;
    
    lblNumber.Text = number;

    compared to:

    SECOND:

    lblNumber.Text = GetValueNbr() + 1:

    The FIRST is easier to read and debug for a developer

    The SECOND is less lines, but then if the developer is working trying to debug a situation to see what GetValueNbr() returns, then it is hard to figure that out.

    This is in a sense of say there are 1,000 variables declared to be set from a method compared to just using the method and not setting the GetValueNbr() to a variable etc.

    Does the C# compiler figure this out and would remove all 1,000 variables?

    Tuesday, April 16, 2019 5:41 PM

All replies

  • User465171450 posted

    I think there will be very little difference as I believe there will be a temporary allocation when doing method() + 1. The garbage collection should handle it without issue though you may have more trouble with the implicit conversion to text.

    Your top can be further shortened though to:

    var number= GetValueNbr();
    
    lblNumber.Text = (++number).ToString();

    I don' t think this reduces the readability though some people get confused on the importance of where the ++ is.

    Tuesday, April 16, 2019 7:54 PM