- Home /
Should I cache simple math?
If I have something like this:
num1 = 10-10/20
num2 = 10/20+1
would there be a performance benefit to caching the "10/20" since I'm using it twice, or would the caching itself be more expensive than just doing the math again?
In general, the answer to this type of question would be: benchmark it.
Answer by elenzil · May 07, 2020 at 06:31 PM
this is a great question.
I would strongly say that from a performance point of view there's no benefit unless this math is being executed more than a thousand times per second and even then it's extremely dubious. If this is literally the math at hand as well, the compiler will convert these expressions into constants at compile-time, so caching the constants in variables could actually decrease your performance.
However, from a code correctness and maintainability point of view, reducing duplication is generally good.
Computers are super fast, so I would definitely prioritize correctness and maintainability over performance.
Right. Also as you already said if an expression consists of only literal values the compiler will actually pre-calculate the expression and just store the result as a single value. In the case of the example code the two lines:
num1 = 10-10/20
num2 = 10/20+1
would actually simplify to
num1 = 10
num2 = 1
since "10/20" is an an integer division it will result in just "0".
edit
I forgot to mention that actual compile time constants that are used in an expression are also pre evaluated at compile time. For example this expression:
public class $$anonymous$$yClass
{
const int v1 = 5;
const int v2 = 10;
static int v3 = 10;
public int resultValue = 3 + v1 * v2 * 2 + v3;
Becomes this after compilation (taken through ILSpy from the compiled assembly)
public class $$anonymous$$yClass
{
private const int v1 = 5;
private const int v2 = 10;
private static int v3 = 10;
public int resultValue = 103 + $$anonymous$$yClass.v3;
As you can see the expression "3 + v1 v2 2" has been reduced to "103". Static variables however are not precalculated since they can actually be changed ar runtime. Even static readonly
variables are not necessarily pre evaluated.