Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Best way of assigning values to strings in a loop

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.

like image 676
Hamid Shahid Avatar asked Nov 28 '22 20:11

Hamid Shahid


1 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.

like image 136
David Schmitt Avatar answered Dec 10 '22 04:12

David Schmitt