Re: [reSIProcate] Minor suggestion to use ++i instead of i++
This has been educational for me. Thanks
On 11/8/04 2:39 AM, "Derek MacDonald" <derek@xxxxxxxx> wrote:
> The only time that there should be a difference between ++i & i++ is if the
> return value is used as an l-value. I tested this with vc++ in release.
>
> Here's the code:
>
> int main()
> {
>
> typedef list<int> ListOfIntegers;
>
> ListOfIntegers vals(100, 10);
>
> ListOfIntegers::iterator i;
> int j=0;
> for( i=vals.begin(); i != vals.end(); )
> {
> i++;
> ++i;
> ListOfIntegers::iterator unusedlvalue = i++;
> ListOfIntegers::iterator lvalue = i++;
> j = j+5;
> j = j + *lvalue;
> }
>
> return j;
> }
>
> Here's the disassembly of the code inside the for loop:
>
> {
> i++;
> 00401860 mov ecx,dword ptr [eax]
> ++i;
> 00401862 mov eax,dword ptr [ecx]
> ListOfIntegers::iterator unusedlvalue = i++;
> 00401864 mov eax,dword ptr [eax]
> ListOfIntegers::iterator lvalue = i++;
> 00401866 mov ecx,eax
> 00401868 mov eax,dword ptr [eax]
> 0040186A cmp eax,esi
> j = j+5;
> j = j + *lvalue;
> 0040186C mov ecx,dword ptr [ecx+8]
> 0040186F lea edi,[edi+ecx+5]
> 00401873 jne main+40h (401860h)
> }
>
> Which matched what I thought; the compiler even distinguished between cases
> when the l-value was used and when it wasn't.
>
> With map<int, int>, things are a little more complicated; the disassembly
> looks very similar except for a lea instruction; i++ actually has 1 less
> instruction than ++i in the dissambly(30 vs 31), and there is lea in
> different places, but I suspect this is well into compiler optimization
> land, and not much to do with the prefix vs postfix; somebody who knows more
> assembly can play with the map result & verify this.
>
> In conclusion, the ++i vs i++ look like folklore, at least on vc++, and
> barring strong profiling results I don't think we should worry about it.
>
>
>
>