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

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

    Try checking the buffer using an int-sized variable where possible (it should be aligned).

    Off the top of my head (uncompiled, untested code follows - there's almost certainly at least one bug here. This just gives the general idea):

    /* check the start of the buf byte by byte while it's unaligned */
    while (size && !int_aligned( buf)) {
        if (*buf != 0) {
            return 0;
        }
    
        ++buf;
        --size;
    }
    
    
    /* check the bulk of the buf int by int while it's aligned */
    
    size_t n_ints = size / sizeof( int);
    size_t rem = size / sizeof( int);
    
    int* pInts = (int*) buf;
    
    while (n_ints) {
        if (*pInt != 0) {
            return 0;
        }
    
        ++pInt;
        --n_ints;
    }
    
    
    /* now wrap up the remaining unaligned part of the buf byte by byte */
    
    buf = (char*) pInts;
    
    while (rem) {
        if (*buf != 0) {
            return 0;
        }
    
        ++buf;
        --rem;
    }
    
    return 1;
    

提交回复
热议问题