Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

double d[10]; int length = 10;  memset(d, length * sizeof(double), 0);  //or  for (int i = length; i--;)   d[i] = 0.0; 
like image 769
vehomzzz Avatar asked Sep 03 '09 13:09

vehomzzz


People also ask

Is memset faster than for loop?

You can assume that memset will be at least as fast as a naive implementation such as the loop. Try it under a debug build and you will notice that the loop is not replaced. That said, it depends on what the compiler does for you. Looking at the disassembly is always a good way to know exactly what is going on.

Does memset work with long long?

memset only uses one byte of the value passed in and does bytewise initialization. If you want to initialize a long long array with a particular value, just use std::fill or std::fill_n and let your library and compiler optimize it as they can (partial loop unrolling etc).

Is memset optimized?

All zeroing operations that the pool allocator performs and many structure/array initializations that InitAll performs end up going through the memset function. Memset is one of the hottest functions on the operating system and is already quite optimized as a result.

Why do we need memset?

memset() is used to fill a block of memory with a particular value. The syntax of memset() function is as follows : // ptr ==> Starting address of memory to be filled // x ==> Value to be filled // n ==> Number of bytes to be filled starting // from ptr to be filled void *memset(void *ptr, int x, size_t n);


2 Answers

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 ); 
like image 148
sharptooth Avatar answered Sep 20 '22 08:09

sharptooth


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.

like image 35
codymanix Avatar answered Sep 21 '22 08:09

codymanix