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

c, c++, optimization, performance

Solution

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.

Problem

``` double d[10]; int length = 10; memset(d, length * sizeof(double), 0); //or for (int i = length; i--;) d[i] = 0.0; ```

Original source