Alex Rivera | Logout

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

Asked 2009-09-03T13:19:07.063
36
double d[10];
int length = 10;

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

//or

for (int i = length; i--;)
  d[i] = 0.0;
Edit
Report

3 Answers

4
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.

answered 2009-09-03T13:23:00.113
3

According to this Wikipedia article on IEEE 754-1975 64-bit floating point a bit pattern of all 0s will indeed properly initialize a double to 0.0. Unfortunately your memset code doesn't do that.

Here is the code you ought to be using:

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

As part of a more complete package...

{
    double *d;
    int length = 10;
    d = malloc(sizeof(d[0]) * length);
    memset(d, 0, length * sizeof(d[0]));
}

Of course, that's dropping the error checking you should be doing on the return value of malloc. sizeof(d[0]) is slightly better than sizeof(double) because it's robust against changes in the type of d.

Also, if you use calloc(length, sizeof(d[0])) it will clear the memory for you and the subsequent memset will no longer be necessary. I didn't use it in the example because then it seems like your question wouldn't be answered.

answered 2009-09-03T15:40:34.700
1

memset(d, 10, 0) is wrong as it only nulls 10 bytes. prefer std::fill as the intent is clearest.

answered 2009-09-03T13:21:12.827

Your Answer