2

my query is- if declaring the variable inside the loop and then using it has any additional overload on the compiler or does declaring once outside the loop and then constantly re-iterating its value inside the loop is a better option in terms of performance of loops having over a million iterations

for example, I have the code snippet

int 1;
for(i=0;i<1000000;i++)
{
      int k;
       //some code that uses k and displays the computed results
}

VS

int i;
int k;
for(i=0;i<1000000;i++)
{
      k=0;
      //copy k from the user as usual and compute and display the results
}

here my main concern is not just about the time taken for both the snippets, if I look at the bigger picture the variable k is still accessed a million times in the second loop as well so if I use RISC or CISC converted code for the same, is "declaring and using" same as "accessing and using" for the processor? does my act of accessing adding the same work as declaring it and then accessing in the loop? which is the better method of the two for efficiency?

  • 1
    Did you try compiling your code and check the assembly differences (if any)? – Dominique May 14 '21 at 09:07
  • 2
    Turn on compiler optimization and it shouldn't matter. – user1937198 May 14 '21 at 09:07
  • 1
    profile it and/or compare the assembly output – Raildex May 14 '21 at 09:07
  • 1
    If anything redeclation may be faster, because it removes the data dependency between loop iterations, making it easier to optimize. – user1937198 May 14 '21 at 09:09
  • 2
    Modern compilers do a significant amount of analysis, and their output will not differ based on whether a variable is declared inside or outside a loop, provided that no use inside the loop mixes with use outside the loop or with other iterations of the same loop and the code is not complicated in ways that prevent the compiler from seeing this. Overall, it is better to declare such a variable inside the loop. One, it reduces errors where something is accidentally used where it was not intended, because it reduces the scope of the variable… – Eric Postpischil May 14 '21 at 09:34
  • 1
    … Two, in cases where the lifetime of assigned values might be obscured from the compiler, defining the variable inside the loop makes it clear. – Eric Postpischil May 14 '21 at 09:34
  • Alright, got the idea – Satyam Dwivedi May 14 '21 at 15:39

0 Answers0