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

后端 未结 20 2326
孤独总比滥情好
孤独总比滥情好 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:59

    If your program is x86 only or x64 only, you can easily optimize using inline assambler. The REPE SCASD instruction will scan a buffer until a non EAX dword is found.

    Since there is no equivalent standard library function, no compiler/optimizer will probably be able to use these instructions (as Confirmed by Sufian's code).

    From the head, something like this would do if your buffer length is 4-bytes aligned (MASM syntax):

    _asm {
       CLD                ; search forward
       XOR EAX, EAX       ; search for non-zero
       LEA EDI, [buf]     ; search in buf
       MOV ECX, [buflen]  ; search buflen bytes
       SHR ECX, 2         ; using dwords so len/=4
       REPE SCASD         ; perform scan
       JCXZ bufferEmpty:  ; completes? then buffer is 0
    }
    

    Tomas

    EDIT: updated with Tony D's fixes

提交回复
热议问题