When is assembly faster than C?

前端 未结 30 2479
挽巷
挽巷 2020-12-02 03:18

One of the stated reasons for knowing assembler is that, on occasion, it can be employed to write code that will be more performant than writing that code in a higher-level

30条回答
  •  攒了一身酷
    2020-12-02 03:58

    I'm surprised no one said this. The strlen() function is much faster if written in assembly! In C, the best thing you can do is

    int c;
    for(c = 0; str[c] != '\0'; c++) {}
    

    while in assembly you can speed it up considerably:

    mov esi, offset string
    mov edi, esi
    xor ecx, ecx
    
    lp:
    mov ax, byte ptr [esi]
    cmp al, cl
    je  end_1
    cmp ah, cl
    je end_2
    mov bx, byte ptr [esi + 2]
    cmp bl, cl
    je end_3
    cmp bh, cl
    je end_4
    add esi, 4
    jmp lp
    
    end_4:
    inc esi
    
    end_3:
    inc esi
    
    end_2:
    inc esi
    
    end_1:
    inc esi
    
    mov ecx, esi
    sub ecx, edi
    

    the length is in ecx. This compares 4 characters at time, so it's 4 times faster. And think using the high order word of eax and ebx, it will become 8 times faster that the previous C routine!

提交回复
热议问题