0

Possible Duplicate:
Declaring a variable inside or outside an foreach loop: which is faster/better?

Hi all,

What is the difference between two examples or is there any?

Ex 1:

for (int i = 0; i < 2; i++)
{
    Thread newThread = new Thread( ... );
    newThread.Start();
}

Ex 2:

Thread newThread;
for (int i = 0; i < 2; i++)
{
    newThread = new Thread( ... );
    newThread.Start();
}

their IL codes are same...

Community
  • 1
  • 1
ogun
  • 1,314
  • 2
  • 16
  • 40
  • yes @dtb mentions an exact dupe, and that one has a more precise answer, saying that both are compiled to the same IL so perf wise no difference. – gideon Jan 25 '11 at 12:39

4 Answers4

3

In the second example, you can access the last thread with newThread, which is not possible in the first example.

One more difference: the second example holds a reference to the last thread, so the garbage collector can't free the memory when the thread finished and could be disposed.

The new keyword allocates the memory, so there is no difference in memory allocation (see this link).

Matten
  • 17,365
  • 2
  • 42
  • 64
  • If the newThread in the second example is not referenced anywhere after that loop, it will be available for garbage collection right away. That is why you need GC.KeepAlive(object) for certain scenarios. – mgronber Jan 25 '11 at 12:55
  • Okay, I thought the reference itself would not allow the GC to collect the field. – Matten Jan 25 '11 at 12:57
2

The only difference is the scope of the newThread variable.

In the first example, it will only be accessible from within the loop; in the second example, you can also access it after the loop.

Limit the scope as much as possible, so if it should only be accessible with in the loop, choose the first, otherwise the second.

Willem van Rumpt
  • 6,490
  • 2
  • 32
  • 44
2

In the first example, newThread is restricted to the scope inside the loop. In the second example, newThread exists in the scope outside the for loop

If you're not using newThread for anything else outside the loop, you should declare it within the loop, so that it's clear you're only using the loop to spawn threads.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

The difference is obviously the scope of the variable.

In the first example, the Thread instance will have no more references after the loop.

In the second example, the Thread instance will still have a reference after the loop, and will only loose that reference when the containing block is ended.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185