Is there any difference between declare variable in/out for? [duplicate]
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...
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).
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.
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.
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.
精彩评论