Influence of constants and variability of operations in C # performance

Constants are often used in C / C ++ programming as a way to get clearer code. Sometimes there may be an optimization advantage. However, I was interested in knowing what benefit could be gained from declaring values ​​that should be readonly or consts in C #, except for more readable code.

Let's say I have the following C # code:

public Double HalfPiSomething(Int32 input)
{
    return input + (Math.PI / 2);
}

This is a fairly simple example, but each time the method is called, we divide Math.PIby 2, add it to the input, and return it to the calling statement.

Take this code and make Math.PI / 2its own variable somewhere in the containing class:

private Double _halfPi = Math.PI / 2;

public Double HalfPiSomething(Int32 input)
{
    return input + _halfPi;
}

, Math.PI / 2 , , ... , .

, _halfPi , const:

private const Double _halfPi = Math.PI / 2;

public Double HalfPiSomething(Int32 input)
{
    return input + _halfPi;
}

, , - # , - - , ? ?

+4
3

, , Math.PI 2, .

, , : # . , , , , , , .

- Math.PI / 2 , , .

, , - # , - - , ?

, , .

?

"" , . ( , ).

+6

JIT. , ,

    public double HalfPiSomething(int input)
    {
        return (double)input + 1.5707963267949;
    }

- , , , , . .

+3

: - const, readonly, / .

, , , , :

const double halfPi = Math.PI / 2;
var r1 = halfPi * 3;    
var r2 = Math.PI / 2 * 3;

r1 r2 .

Readonly - , JIT, - .

0
source

Source: https://habr.com/ru/post/1548521/


All Articles