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?

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.