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

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

    Edit: Bad answer

    A novel approach might be

    int is_empty(char * buf, int size) {
        char start = buf[0];
        char end = buff[size-1];
        buf[0] = 'x';
        buf[size-1] = '\0';
        int result = strlen(buf) == 0;
        buf[0] = start;
        buff[size-1] = end;
        return result;
    }
    

    Why the craziness? because strlen is one of the library function that's more likely to be optimized. Storing and replacing the first character is to prevent the false positive. Storing and replacing the last character is to make sure it terminates.

提交回复
热议问题