performance - Does it matter where I put the declaration of a variable? -


suppose have following 2 examples, there difference between putting variable declaration outside of loop vs inside loop, performance wise? note: new object being created inside loop.

method 1:  foreach (string name in namelist) {     person person1 = new person();     person1.fullname = name; }  method 2: person person1 = null; foreach (string name in namelist) {     person1 = new person();     person1.fullname = name; } 

it's micro-optimization. no, performance wise, doesn't matter. difference in performance made irrelevant in practically non-trivial programs. , it's entirely possible optimizer convert less efficient form more efficient form (don't ask me which).

i'd prefer first since it's slightly less code , limiting variable scope as possible considered practice.

actually, more similar method 1, method 2 should this:

person person1 = null; foreach (string name in namelist) {     person1 = new person();     person1.fullname = name; } person1 = null; 

because after loop, person1 still point object created in last iteration, garbage collector able free object once person1 leaves scope or assigned different value (i.e. null). if in terminating code block doesn't else, leave scope @ end of block, null assignment not necessary.


Comments

Popular posts from this blog

HTTP/1.0 407 Proxy Authentication Required PHP -

curl - PHP fsockopen help required -

c# - Resource not found error -