Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference type variable recycling - is a new reference variable created every loop in a loop if declared therein?

Tags:

c#

oop

Is the following:

MyObject myVariable; for(int i = 0; i < objects.Length, i++){   myVariable = objects[i];   // do stuff... } 

more efficient then:

for(int i = 0; i < objects.Length, i++){   MyObject myVariable = objects[i];   // do stuff... } 

because a new variable to hold a reference is not created every time? (or is the complier intelligent enough just to use the same variable)..

(If a new variable is created is it malloced on the heap?)

like image 947
markmnl Avatar asked Sep 12 '11 03:09

markmnl


1 Answers

No, "variables" exist almost entirely for the sake of the programmer. You're not creating any additional work at run-time by declaring the variable inside the method.

In theory, the compiler will set aside space on the stack when a method is called for each variable declared in that method. So the presence of that variable in the method would be more important than its scope. No space is allocated on the heap unless the new keyword is used.

In practice, the compiler can identify variables that have such a short scope that they can be stored in a register on the CPU instead of needing space on the stack. For example:

var a = b[c]; a.ToString(); // never access "a" again. 

... would be the same as:

b[c].ToString(); 

... because the compiler recognizes that it only needs to store the result of b[c] long enough to call a method on it, so it can just use a CPU register instead of using memory.

For this reason, declaring your variable inside the loop could actually cause the method to allocate less stack space for the variable, depending on the possible logic flow afterward. However, that gets into huge micro-optimization that doesn't make any sense for most people to care about.

Update

Since some people still seem to think that declaring a variable in a loop has some effect, I guess I need to provide proof. Type the following programs into LINQPad.

int j; for(int i = 0; i < 5; i++) {     j = i; } 

... and...

for(int i = 0; i < 5; i++) {     int j = i; } 

Execute the code, then go to the IL tab to see the generated IL code. It's the same for both of these programs:

IL_0000:  ldc.i4.0     IL_0001:  stloc.0      IL_0002:  br.s        IL_0008 IL_0004:  ldloc.0      IL_0005:  ldc.i4.1     IL_0006:  add          IL_0007:  stloc.0      IL_0008:  ldloc.0      IL_0009:  ldc.i4.5     IL_000A:  blt.s       IL_0004 

So there's incontrovertible proof that this will make no difference at compile time. You'll get exactly the same compiled IL from both programs.

like image 172
StriplingWarrior Avatar answered Sep 23 '22 21:09

StriplingWarrior