a) for (int nIdx = 0; nIdx < 1000; ++nIdx) {...};
b) for (int nIdx = 0; nIdx < 1000; nIdx++) {...};
a is the correct answer. ++nIdx results in the following
equivalent code.
nIdx = nIdx + 1;
return nIdx;
Where as nIdx++ generate the following code.
var tmp = nIdx;
nIdx = nIdx + 1;
return tmp;
As a result the first code block generates less code and requires no temporary variables. You should prefer the first form whenever possible. Note that the C# compiler
is smart enough to optimize some common cases but it is always better to write efficient
code when it can be done easily and cleanly.
(Updated 28 Dec 2006 w/ comments received from James Curran)