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

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

    What about looping from size to zero (cheaper checks):

    int is_empty(char * buf, int size) 
    {
        while(size --> 0) {
            if(buf[i] != 0) return 0;
        }
        return 1;
    }
    

    It must be noted that we probably cannot outperform the compiler, so enable the most aggressive speed optimization in your compiler and assume that you're likely to not go any faster.

    Or handling everything using pointers (not tested, but likely to perform quite good):

    int is_empty(char* buf, int size)
    {
        char* org = buf;
    
        if (buf[size-1] == 1)
            return 0;
    
        buf[size-1] = 1;
        while(! *buf++);
        buf--;
    
        return buf == org[size-1];
    }
    

提交回复
热议问题