Which is faster/preferred: memset or for loop to zero out an array of doubles?

38,438

Solution 1

Note that for memset you have to pass the number of bytes, not the number of elements because this is an old C function:

memset(d, 0, sizeof(double)*length);

memset can be faster since it is written in assembler, whereas std::fill is a template function which simply does a loop internally.

But for type safety and more readable code I would recommend std::fill() - it is the c++ way of doing things, and consider memset if a performance optimization is needed at this place in the code.

Solution 2

If you really care you should try and measure. However the most portable way is using std::fill():

std::fill( array, array + numberOfElements, 0.0 );

Solution 3

Try this, if only to be cool xD

{
    double *to = d;
    int n=(length+7)/8;
    switch(length%8){
        case 0: do{ *to++ = 0.0;
        case 7:     *to++ = 0.0;
        case 6:     *to++ = 0.0;
        case 5:     *to++ = 0.0;
        case 4:     *to++ = 0.0;
        case 3:     *to++ = 0.0;
        case 2:     *to++ = 0.0;
        case 1:     *to++ = 0.0;
        }while(--n>0);
    }
}

Solution 4

Assuming the loop length is an integral constant expression, the most probable outcome it that a good optimizer will recognize both the for-loop and the memset(0). The result would be that the assembly generated is essentially equal. Perhaps the choice of registers could differ, or the setup. But the marginal costs per double should really be the same.

Solution 5

memset(d,0,10*sizeof(*d));

is likely to be faster. Like they say you can also

std::fill_n(d,10,0.);

but it is most likely a prettier way to do the loop.

Share:
38,438
vehomzzz
Author by

vehomzzz

He adapts a lazy approach to a complex learning. His eclectic personality coupled with eccentric character caused much harm to masses, and to himself.

Updated on September 15, 2020

Comments

  • vehomzzz
    vehomzzz over 3 years
    double d[10];
    int length = 10;
    
    memset(d, length * sizeof(double), 0);
    
    //or
    
    for (int i = length; i--;)
      d[i] = 0.0;