I wonder what is the most efficient way of assigning string variables in a loop. So, for example if I have to browse through a list of nodes and assigning the value of the node to a string, would it be better if I define a variable before the loop starts like
string myStringVariable = string.Empty
foreach(XmlNode node in givenNodes)
{
myStringVariable = node.Value;
....
...
}
or would it be more efficient if I define the variable inside the loop like
foreach(XmlNode node in givenNodes)
{
string myStringVariable = node.Value;
....
...
}
I think the first approach is more efficient while the second looks more elegant. Is there a performance difference between the two?
Thanks for you answers.
With modern compilers this doesn't make any performance difference at all and you should always use the way that best matches your algorithm. That is, prefer the second variant if you don't need the variable's value from the last iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With