Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more efficient way to assign values to variables in .NET?

This is something that I have always wondered about, but never bothered to profile.

Is it more efficient to assign a value to a temp variable, than to keep using that value. An Example may be clearer:

string s = reader.GetItem[0].ToString();
someClass.SomeField  = s;
someOtherClass.someField = s;

OR

someClass.SomeField  = reader.GetItem[0].ToString();
someOtherClass.someField = reader.GetItem[0].ToString();

My initial thought would the top example would be more efficient as it doesn't have to access the Item collection or call ToString.

Would be interested to hear other peoples ideas, or definitive answer either way.

like image 893
JamesSugrue Avatar asked Oct 28 '08 01:10

JamesSugrue


2 Answers

The compiler cannot know if the expression on the right-hand-side has side-effects, so it must re-evaluate it if you code it twice. Hence the first is more efficient in the sense that it will not re-do the GetItem & ToString calls.

So if you the programmer know that these calls are pure/idempotent, then you should write the code the first way.

like image 95
Brian Avatar answered Nov 08 '22 05:11

Brian


As Brian said, the first way will be more efficient, though whether it makes much difference in the real world depends on how expensive the duplicated functions are, and how frequently this piece of code as a whole is called.

However, as well as being more efficient, the first way better indicates intention - that you mean to assign the same value to the two things. It also aids maintainability because if it needs to change, you only need to change it in one place. For me, both of these are typically more important than efficiency.

like image 28
Greg Beech Avatar answered Nov 08 '22 06:11

Greg Beech