What are the differences between using array offsets vs pointer incrementation?

后端 未结 11 1192
醉话见心
醉话见心 2021-02-06 13:39

Given 2 functions, which should be faster, if there is any difference at all? Assume that the input data is very large

void iterate1(const char* pIn, int Size)
{         


        
11条回答
  •  清歌不尽
    2021-02-06 14:23

    Several years ago I asked this exact question. Someone in an interview was failing a candidate for picking the array notation because it was supposedly obviously slower. At that point I compiled both versions and looked at the disassembly. There was one opcode extra in the array notation. This was with Visual C++ (.net?). Based on what I saw I concluded that there is no appreciable difference.

    Doing this again, here is what I found:

        iterate1(arr, 400); // array notation
    011C1027  mov         edi,dword ptr [__imp__printf (11C20A0h)] 
    011C102D  add         esp,0Ch 
    011C1030  xor         esi,esi 
    011C1032  movsx       ecx,byte ptr [esp+esi+8] <-- Loop starts here
    011C1037  push        ecx  
    011C1038  push        offset string "%c" (11C20F4h) 
    011C103D  call        edi  
    011C103F  inc         esi  
    011C1040  add         esp,8 
    011C1043  cmp         esi,190h 
    011C1049  jl          main+32h (11C1032h) 
    
        iterate2(arr, 400); // pointer offset notation
    011C104B  lea         esi,[esp+8] 
    011C104F  nop              
    011C1050  movsx       edx,byte ptr [esi] <-- Loop starts here
    011C1053  push        edx  
    011C1054  push        offset string "%c" (11C20F4h) 
    011C1059  call        edi  
    011C105B  inc         esi  
    011C105C  lea         eax,[esp+1A0h] 
    011C1063  add         esp,8 
    011C1066  cmp         esi,eax 
    011C1068  jne         main+50h (11C1050h) 
    

提交回复
热议问题