I wanted to find out what more efficient (if even) in the following code
Value type
ForEach(string s in strings)
{
string t = s;
}
// or
string t;
ForEach(string s in strings)
{
t = s;
}
and is there a different with reference types.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The two code snippets produce exactly the same IL. Here’s the C# code I used to test with:
And here’s the resulting IL for both methods after compiling with optimizations enabled:
As usual, the rule is the same: trust your compiler. Let it handle these optimizations for you, rather than trying to worry about it as you write the code. Just write the code that makes sense and is readable.
Most importantly, ignore all the people who argue that one of them is “theoretically” better than the other. That’s pure nonsense. There’s no theory that’s relevant until after the code is compiled. And since it compiles down to the exact same thing, it’s guaranteed to be completely identical in performance.
But if you still don’t believe my urgings to trust your compiler (some of us are stubborn, I know because even I still am sometimes), at least you now know how to answer these types of questions on your own. Write some sample code that demonstrates both variations, compile it in “Release” mode, then open up the assembly in ILDASM.exe and compare the resulting IL code for yourself. Things like this are so easy to test, there’s never a reason to guess.