-5

With a nested for loop like:

for (int i=0; i<N; i++)
    for (int j=0; j<N; j++)

Is it better to do:

for (int i=0, j; i<N; i++)    //Declare them both at once
    for (j=0; j<N; j++)

because declaring j over and over again will create space on stack and discard repeatedly? For both small and large programs.

  • 1
    Both yes and no. Yes, the second is a little better - **but** - the Java compiler is quite capable of reordering the declarations in a way that makes sense (in practice, they're the same). – Elliott Frisch Oct 09 '17 at 02:11
  • JavaScript doesn't have an `int` type, and if you use `var` it doesn't have block score so doesn't really declare the variable multiple times. – nnnnnn Oct 09 '17 at 02:14
  • With `let` and `const` you can't re-declare a variable – Sterling Archer Oct 09 '17 at 02:22
  • P.S. If you're concerned about performance you can always test the relative performance, e.g. for JS try https://jsperf.com/. @SterlingArcher - OP means that declaring the variable in the inner loop would recreate it on each iteration of the outer loop, not that they're declaring other variables with that name in the same scope. – nnnnnn Oct 09 '17 at 02:45
  • 1
    Perhaps you could remove the tags for the languages you're not interested in. – Dawood ibn Kareem Oct 09 '17 at 03:15

1 Answers1

0

Yes declaration should be made only once because declaring once and using that again makes sense and it should be done because if you are declaring again and again then the last memory allocation to that variable is not removed yet and you are creating more memory for that without any use. In case of Definition, you define again and again, you just access that location and change the value that is more of a better way then declaring the same variable again.

Aniruddh Agarwal
  • 900
  • 1
  • 7
  • 22
  • Which languages does your answer apply to? I don't think it's true of Java. I'm not expert in JavaScript or PHP so I can't comment about those. It's unfortunate that OP asked about three different languages in one question. – Dawood ibn Kareem Oct 09 '17 at 03:31
  • Memory allocation would never get removed. This will make a difference when executing programs with greater loops. Thank you very much. – Mike Mendizabal Oct 12 '17 at 03:31