VM Question

Say I have code like this:
X + Y - 10;

Say I run that in my main game loop (few hundred times per second if not more).

Say neither X or Y change in a great while. Will that get calculated each time or is it smart enough to cache that internally and only recalculate it if either X or Y has changed?

Your statement is dead code (doesn’t assign the result to anything). It will get removed in the first iteration of optimization and never get executed.

If however you meant:

Z=X+Y+10;

And x and y are not getting updated often, it will probably still fully evaluate the expression because X & Y can change and it simply won’t be able to work out when.

Yeah, also I would honestly doubt you have to optimize THAT part.
Because addition is really not that expensive and in order to ‘optimize’ it the introduced code (around that block) would probably cost the same as just doing the math.

BUT if you REALLY want to:

  • store the value of Z in a field
  • create setters for X and Y and when one of them gets set, recalculate Z
  • use the field
  • partay!