Faster approach to checking for an all-zero buffer in C?

后端 未结 20 2402
孤独总比滥情好
孤独总比滥情好 2020-12-03 05:33

I am searching for a faster method of accomplishing this:

int is_empty(char * buf, int size) 
{
    int i;
    for(i = 0; i < size; i++) {
        if(buf[         


        
20条回答
  •  无人及你
    2020-12-03 05:58

    For something so simple, you'll need to see what code the compiler is generating.

    $ gcc -S -O3 -o empty.s empty.c
    

    And the contents of the assembly:

            .text
            .align 4,0x90
    .globl _is_empty
    _is_empty:
            pushl       %ebp
            movl        %esp, %ebp
            movl        12(%ebp), %edx  ; edx = pointer to buffer
            movl        8(%ebp), %ecx   ; ecx = size
            testl       %edx, %edx
            jle L3
            xorl        %eax, %eax
            cmpb        $0, (%ecx)
            jne L5
            .align 4,0x90
    L6:
            incl        %eax            ; real guts of the loop are in here
            cmpl        %eax, %edx
            je  L3
            cmpb        $0, (%ecx,%eax) ; compare byte-by-byte of buffer
            je  L6
    L5:
            leave
            xorl        %eax, %eax
            ret
            .align 4,0x90
    L3:
            leave
            movl        $1, %eax
            ret
            .subsections_via_symbols
    

    This is very optimized. The loop does three things:

    • Increase the offset
    • Compare the offset to the size
    • Compare the byte-data in memory at base+offset to 0

    It could be optimized slightly more by comparing at a word-by-word basis, but then you'd need to worry about alignment and such.

    When all else fails, measure first, don't guess.

提交回复
热议问题