JavaSa
JavaSa

Reputation: 6241

Defining a variable inside a loop vs outside

I wanted to know in each couple of loop code, whether some version consumes less memory than the second one, and if it's true that in some versions we allocated new space for a variable in each loop cycle.

Note: 2 is pretty obvious, 1 and 3 are more interesting..

1.

While(!exit)
{
  int x = 5;
}

Versus:

int x= 0;
While(!exit)
{
  x = 5;
}

Same question for reference types: 2.

While(!exit)
{
      Point p = new Point();
      p.x = 5;
}

Versus:

Point p = new Point();
While(!exit)
{
      p.x = 5;
}

3. Reference type without allocation similar to 1?:

While(!exit)
{
      Point p = point1;
}

Versus:

Point p = null;
While(!exit)
{
   p = point1;
}

Upvotes: 3

Views: 174

Answers (3)

user1178729
user1178729

Reputation:

It doesn't matter. The compiler optimises it, so it stays the same. It should not affect performance at all, in compiled languages like C#. In Java, for example, it is better to declare only once.

Upvotes: 0

CharlesW
CharlesW

Reputation: 625

The proper way to tell is to disassemble it, and look at the code. You'll see references to each.

Link to MSDN way to do it: http://msdn.microsoft.com/en-us/library/f7dy01k1.aspx

The code is pretty readable in CIL. Just search for function name, you'll see the call to new and such.

Upvotes: 0

Tergiver
Tergiver

Reputation: 14507

The compiler decides how many stack storage locations your function needs and will do what it can to reduce that need. Something like:

{
   int a;
   ...
}
{
   int b;
   ...
}

Seems to require two storage locations, but the compiler can see that the first is never used outside the first scope and can re-use the location for b.

It may also see that it can do away with the stack storage all together and perform the whole thing in registers.

Whether looping or not, a single variable declaration defines a single storage location. It would never be the case that a new storage location would get created for each iteration of the loop.

In general, this is not something you need to be concerned with.

Note that "debug" builds might produce separate storage locations on the stack for every variable declared to make viewing those variables while debugging easier.

Upvotes: 4

Related Questions