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