Difference between declaring variables before or in loop?

can you declare variables in a for loop
declare variable in loop c
access variable outside for loop java
java variable declaration inside loop
declare variable in while loop c++
variable within for loop
c declare variable in while loop
c++ variable defined 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.

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.

Does it make a difference if I declare variables inside or outside a , However, there is an important difference between this program fragment and the previous one: Scope Rule: a variable declared in a for statement can only be� 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);}

Well I ran your A and B examples 20 times each, looping 100 million times.(JVM - 1.5.0)

A: average execution time: .074 sec

B: average execution time : .067 sec

To my surprise B was slightly faster. As fast as computers are now its hard to say if you could accurately measure this. I would code it the A way as well but I would say it doesn't really matter.

Declaring the Loop Control Variable, 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� Since the variable is global, another loop using it would interact with the first one, probably in undesirable ways. And you can't declare a loop control variable with "let" inside the loop block as it will not be accessible from the loop context.

It depends on the language and the exact use. For instance, in C# 1 it made no difference. In C# 2, if the local variable is captured by an anonymous method (or lambda expression in C# 3) it can make a very signficant difference.

Example:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        List<Action> actions = new List<Action>();

        int outer;
        for (int i=0; i < 10; i++)
        {
            outer = i;
            int inner = i;
            actions.Add(() => Console.WriteLine("Inner={0}, Outer={1}", inner, outer));
        }

        foreach (Action action in actions)
        {
            action();
        }
    }
}

Output:

Inner=0, Outer=9
Inner=1, Outer=9
Inner=2, Outer=9
Inner=3, Outer=9
Inner=4, Outer=9
Inner=5, Outer=9
Inner=6, Outer=9
Inner=7, Outer=9
Inner=8, Outer=9
Inner=9, Outer=9

The difference is that all of the actions capture the same outer variable, but each has its own separate inner variable.

Declaring Loop Control Variables Inside the for Loop, Why you should stop declaring variables inside a for loop (especially in JavaScript) 1) You're not recording the heap before hand, so it's impossible to measuring the difference, I saw no difference; the amount of memory� @nawfal: My point is that there weren't any language features in C# 1.0 where you could tell the difference between declaring a variable inside a loop and declaring it outside (assuming that both compiled). That changed in C# 2.0. No bug. – Jon Skeet Jul 8 '14 at 18:40

The following is what I wrote and compiled in .NET.

double r0;
for (int i = 0; i < 1000; i++) {
    r0 = i*i;
    Console.WriteLine(r0);
}

for (int j = 0; j < 1000; j++) {
    double r1 = j*j;
    Console.WriteLine(r1);
}

This is what I get from .NET Reflector when CIL is rendered back into code.

for (int i = 0; i < 0x3e8; i++)
{
    double r0 = i * i;
    Console.WriteLine(r0);
}
for (int j = 0; j < 0x3e8; j++)
{
    double r1 = j * j;
    Console.WriteLine(r1);
}

So both look exactly same after compilation. In managed languages code is converted into CL/byte code and at time of execution it's converted into machine language. So in machine language a double may not even be created on the stack. It may just be a register as code reflect that it is a temporary variable for WriteLine function. There are a whole set optimization rules just for loops. So the average guy shouldn't be worried about it, especially in managed languages. There are cases when you can optimize manage code, for example, if you have to concatenate a large number of strings using just string a; a+=anotherstring[i] vs using StringBuilder. There is very big difference in performance between both. There are a lot of such cases where the compiler cannot optimize your code, because it cannot figure out what is intended in a bigger scope. But it can pretty much optimize basic things for you.

Discussion of Why you should stop declaring variables inside a for , Variables declared inside a method have method level scope and can't be above code uses this keyword to differentiate between the local and class variables. carefully, inner loop will terminate before the outer loop variable is declared. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).

This is a gotcha in VB.NET. The Visual Basic result won't reinitialize the variable in this example:

For i as Integer = 1 to 100
    Dim j as Integer
    Console.WriteLine(j)
    j = i
Next

' Output: 0 1 2 3 4...

This will print 0 the first time (Visual Basic variables have default values when declared!) but i each time after that.

If you add a = 0, though, you get what you might expect:

For i as Integer = 1 to 100
    Dim j as Integer = 0
    Console.WriteLine(j)
    j = i
Next

'Output: 0 0 0 0 0...

Scope of Variables In Java, Redeclaration of a variable in initialization block : Suppose, an initialization vaiable is already declared as integer. Can we re-declare it in for loop with other � Declaring & initializing C Variable. First, you need to declare a variable in the C program before to use it. Memory space is not created for a variable during a declaration. It happens only on the variable definitions. Variable initialization assigs a value to the variable.

For Loop in Java, As well, line is an example of a loop variable declared and initialized outside the loop. Note that this example uses JDK 6, simply to illustrate the point. In JDK 7, try � The difference comes probably from the difference in scope. The smaller the scope the more likely the compiler is able to eliminate serialization of the variable. In the small loop scope, the variable was likely put in a register and not saved on the stack frame.

Java Practices->Don't declare local variables before use, It is because you want to limit the "affected scope" of a variable in a loop ( constantly changing). You m What is difference between while loop and for loop? Using the incrementor before a variable will first increment the value of the variable and then use this value. Using the incrementor after a variable will use the current value of the variable, and then increment the variable after. This is generally just a shortcut or "code-condenser".

Is it better to declare a repeatedly-used variable inside a loop or , My professor says it is much better practice to declare all variables at the beginning of a block What is the difference between 'while' loop and 'for' loop? in a for statement is the whole function, you will get an error if you reference it before .

Comments
  • This matters when writing Java code for the Android platform. Google suggests that for time-critical code to declare incrementing variables outside of a for-loop, as if inside the for-loop, it re-declares it each time in that environment. The performance difference is very noticeable for expensive algorithms.
  • @AaronCarson could you please provide link to this suggestion by Google
  • Instead of Double, if it deals with String, still the case "b" better?
  • @Antoops - yes, b is better for reasons that have nothing to do with the data type of the variable being declared. Why would it be different for Strings?
  • You beat me I was just about to post my results for profiling, I got more or less the same and yes surprisingly B is faster really would have thought A if I had needed to bet on it.
  • Not much surprise - when variable is local to the loop, it does not need to be preserved after each iteration, so it can stay in a register.
  • +1 for actually testing it, not just an opinion/theory the OP could have made up himself.
  • @GoodPerson to be honest, I'd like that to be done. I ran this test around 10 times on my machine for 50,000,000-100,000,000 iterations with almost an identical piece of code (that I would love to share with anyone who wants to run stats). The answers were split almost equally either way usually by a margin of 900ms (over 50M iterations) which isn't really much. Though my first thought is that it's going to be "noise", it might lean one by just a bit. This effort seems purely academic to me though (for most real life applications).. I'd love to see a result anyway ;) Anyone agree?
  • Showing test results without documenting the setup, is worthless. That’s especially true in this case, where both code fragments produce identical bytecode, so any measured difference is just a sign of insufficient test conditions.
  • in example B (original question), does it actually creates a new variable each time ? what happening in the eyes of the stack ?
  • @Jon, was it a bug in C# 1.0? Shouldn't ideally Outer be 9?
  • @nawfal: I don't know what you mean. Lambda expressions weren't in 1.0... and Outer is 9. What bug do you mean?