Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)
recategorized by

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.

 I am especially interested in the Java case.

1 Answer

0 votes
by (46k points)
From a review prospect, you'd have to hold it. (And in my theory, if you can hold a difference, the compiler isn't very great).
From a preservation viewpoint, b is better. Maintain and initialize variables in the identical place, in the smallest scope workable. Don't give a gaping hole between the report and the initialization, and don't contaminate namespaces you don't require to.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 27, 2019 in Java by Ritik (3.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...