I have some C# code that performs some calculation involving primitive data types, such as:
public sealed class Calculation
{
private readonly int a, b, c;
public Calculation(int _a, int _b, int _c)
{
this.a = _a; this.b = _b; this.c = _c;
}
public int DoCalculation(int rfactor, int lfactor)
{
return (a / rfactor) + (b / lfactor) + ((a/b)*(rfactor+lfactor));
}
}
If {a,b,c} were compile time constants the expression in the DoCalculation(…) method could be hugely optimized at the CIL level. I am wondering if the JITer will optimize the DoCalculation(…) method similarly to the compile time constant optimizations given the “readonly” hint.
Your example is not a great one, but yes, this kind of optimization certainly happens. At more than one level, the C# compiler gets a shot first. It will evaluate simple expressions with literal values and replace them with the result. Also the way that it can detect overflow at compile time.
The jitter optimizer does this too, normally as a result of inlining methods. But that won’t happen for your DoCalculation() method, it is too complicated to allow inlining. But a trivial one like:
Will certainly get inlined and optimized. Like Console.WriteLine(Calculation.DoCalculation(4, 5)) generates:
Note how the result, 4 * 5 = 20 = 0x14 got precomputed.
There are no hard rules for when exactly the method can get inlined and how involved the expression can be before the optimizer gives up. This is subject to change and depends on the kind of jitter (x86 vs x64 vs ARM).
If this code lives deep inside your critical path and a profiler told you that it is responsible for 80+% of the execution time (don’t skip the profiler!) then it is can be worth your time to tinker with the method and see what you get. Debug the Release mode build and be sure to allow the optimizer to run. Tools + Options, Debugging, General, untick the “Suppress JIT optimization on module load” option.
Small changes can have big effects, feels pretty good when you get to double the speed of your code with a seemingly trivial edit. Or not and you get nowhere after a day of trying, no guarantees. But you’ll certainly develop a “feel” for what kind of code runs well, an experience and insight that is very valuable.