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

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

    Inline assembly version of the initial C code (no error checking, if uiSize is == 0 and/or the array is not allocated exceptions will be generated. Perhaps use try {} catch() as this might be faster than adding a lot of check to the code. Or do as I do, try not to call functions with invalid values (usually does not work). At least add a NULL pointer check and a size != 0 check, that is very easy.

     unsigned int IsEmpty(char* pchBuffer, unsigned int uiSize)
     {
        asm {
          push esi
          push ecx         
    
          mov esi, [pchBuffer]
          mov ecx, [uiSize]
    
          // add NULL ptr and size check here
    
          mov eax, 0
    
        next_char:
          repe scasb           // repeat string instruction as long as BYTE ptr ds:[ESI] == 0
                               // scasb does pointer arithmetic for BYTES (chars), ie it copies a byte to al and increments ESI by 1
          cmp cx,0             // did the loop complete?
          je all_chars_zero    // yes, array is all 0
          jmp char_not_zero    // no, loop was interrupted due to BYTE PTR ds:[ESI] != 0
    
        all_chars_zero:        
          mov eax, 1           // Set return value (works in MASM)
          jmp end  
    
        char_not_zero:
          mov eax, 0          // Still not sure if this works in inline asm
    
        end:
          pop ecx
          pop esi          
      }
    }
    

    That is written on the fly, but it looks correct enough, corrections are welcome. ANd if someone known about how to set the return value from inline asm, please do tell.

提交回复
热议问题