double d[10]; int length = 10; memset(d, length * sizeof(double), 0); //or for (int i = length; i--;) d[i] = 0.0;
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.
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).
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.
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);
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 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With