Effect of consts and variablization of operations in C# performance
c#, c++, optimization, performance
Solution
each time the method is called, we divide `Math.PI` by `2`, add it to input, and return it to the calling statement.
No, that is not what is going on: C# compiler evaluates constant expressions at compile time. Moreover, when an expression that mixes constants and non-constants has sub-expressions that can be computed at compile time, the compiler precomputes the value as if it were a single constant.
The compiler identifies the `Math.PI / 2` sub-expression as a constant, performs the calculation, and produces the code that adds the input to a pre-computed result of the division.
What I want to know is, other than being good coding practice for C# and making code easier to understand and harder to make errors with, are there benefits - especially regarding performance - to doing what I did above?
No, there is no reason to do compiler's job, unless it leads to more clarity.
Does the value stay in local memory longer?
Constant values get "baked into" the code generated by the compiler. They are not part of the local data memory (although they are definitely in memory, for as long as the code is in memory).
Problem
Constants are often used in C/C++ programming as a way of producing clearer code. There may sometimes be an optimization benefit as well. However, I was wondering just what benefit can be gleaned from declaring values to be readonly or consts in C#, aside from more readable code. Let's say I have the following C# code: ``` public Double HalfPiSomething(Int32 input) { return input + (Math.PI / 2); } ``` It's a fairly simple example, but each time the method is called, we divide `Math.PI` by 2, add it to input, and return it to the calling statement. Let's take that code and make the `Math.PI / 2` its own variable somewhere in the containing class: ``` private Double _halfPi = Math.PI / 2; public Double HalfPiSomething(Int32 input) { return input + _halfPi; } ``` Obviously, taking the operation of `Math.PI / 2` and placing it in its own variable is a good idea just as basic coding practice, especially if said value is used in multiple points in the class... It's not here, but let's just pretend. Finally, since `_halfPi` never changes let's make it `const`: ``` private const Double _halfPi = Math.PI / 2; public Double HalfPiSomething(Int32 input) { return input + _halfPi; } ``` What I want to know is, other than being good coding practice for C# and making code easier to understand and harder to make errors with, are there benefits - especially regarding performance - to doing what I did above? Does the value stay in local memory longer?