Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between declaring variables before or in loop?

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (quite pointless) example in Java:

a) declaration before loop:

double intermediateResult; for(int i=0; i < 1000; i++){     intermediateResult = i;     System.out.println(intermediateResult); } 

b) declaration (repeatedly) inside loop:

for(int i=0; i < 1000; i++){     double intermediateResult = i;     System.out.println(intermediateResult); } 

Which one is better, a or b?

I suspect that repeated variable declaration (example b) creates more overhead in theory, but that compilers are smart enough so that it doesn't matter. Example b has the advantage of being more compact and limiting the scope of the variable to where it is used. Still, I tend to code according example a.

Edit: I am especially interested in the Java case.

like image 656
Rabarberski Avatar asked Jan 02 '09 16:01

Rabarberski


People also ask

Should I declare variable in loop or outside?

Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used).

Should I declare variable before loop?

As a general rule, I declare my variables in the inner-most possible scope. So, if you're not using intermediateResult outside of the loop, then I'd go with B. Show activity on this post. A co-worker prefers the first form, telling it is an optimization, preferring to re-use a declaration.

Is it OK to declare a variable inside a for loop?

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.

Should you declare all variables at the beginning?

Rationale: It's best to declare variables when you first use them to ensure that they are always initialized to some valid value and that their intended use is always apparent.


1 Answers

Which is better, a or b?

From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).

From a maintenance perspective, b is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't leave a gaping hole between the declaration and the initialization, and don't pollute namespaces you don't need to.

like image 174
Daniel Earwicker Avatar answered Oct 10 '22 11:10

Daniel Earwicker