0

if I have the following code:

int p=something
int l=somethingelse

int sum=0;
for(int i=0;i<p-l;i++)
    sum+=(~i)^2+1337

can I generally assume the compiler optimizes the code so that p-l aren't recalculated every loop and is just cached since neither is changed in the loop? Or do I have to put p-l into a seperate variable if I want optimal performance?

user2741831
  • 2,120
  • 2
  • 22
  • 43
  • You can check it for yourself by compiling and then decompiling. My guess is that it will not. What if `p` and `l` gets modified by another thread while the loop is running? If you make `p` and `l` `final` though, the compiler might do something different. – Sweeper Dec 13 '19 at 21:29
  • What do you mean by *every loop*? Is this part of a function that is being called? – jrook Dec 13 '19 at 21:31
  • compile it and have a look! – Jocke Dec 13 '19 at 21:32
  • Optimal performance is hardly ever the right goal. Aim for readability and clarity. They're far, far, *far* more important. Arbitrary microoptimizations are anathema to readability. – John Kugelman Dec 13 '19 at 21:34
  • @jrook it has to check the loop condition every time to see if it needs to exit the loop, so it has to recalculate p-l – user2741831 Dec 13 '19 at 21:43

0 Answers0