开发者

creating strings inside a for each loop? or creat them outside, use inside?

开发者 https://www.devze.com 2023-01-30 13:15 出处:网络
i have the following code below and was lookign to clean it up, but am not sure if it needs 开发者_JAVA百科clean up or not.

i have the following code below and was lookign to clean it up, but am not sure if it needs 开发者_JAVA百科clean up or not.

foreach (SearchResult sr in mySrchColl)
{
    string strValIn = sr.Properties["in"][0].ToString();
    string strValOut= sr.Properties["out"][0].ToString();
}

do i change this to something like this:

string strValIn = "";
string strValOut= "";

foreach (SearchResult sr in mySrchColl)
            {
                strValIn = sr.Properties["in"][0].ToString();
                strValOut= sr.Properties["out"][0].ToString();
}

whats the difference or are these two identical?


In the first code segment, the variables will be accessible only within the loop. In the second code segment, they can be accessed outside the loop. This is known as Programming Scope


They compile down to the same IL...no performance difference. It would only be readability; if only used in the foreach...keep the declaration in there.


Difference between declaring variables before or in loop?


If you don't capture the variables into a lambda / anon method it won't make any difference. Inside is arguably cleaner.

As a side note; even if you declare them outside; you don't need to initialize it there; the following is valid:

string s;
foreach(...) {
    s = ...
}

I would still declare inside though :)


In dotnet strings are immutable, so both of the example codes are going to create new objects and assign them to the 2 variables. As such if you are not using those 2 variables outside the foreach loop there isnt going to be much difference.


I think the second one is better. Because in first one, you are creating reference and object of string in loop...whereas in second case , you are just creating ' object of string' and references are just changing...

0

精彩评论

暂无评论...
验证码 换一张
取 消