What is the fastest way to nullify an existing array?

I have an existing 1D array, is memset the fastest way to reset it?

+3
source share
2 answers

The fastest ... maybe yes. Buggy is almost sure!

It basically depends on the implementation, the platform, and ... what type the array contains.

In C ++, when a variable is defined, its constructor is called. When an array is specified, all array element constructors are called.

Clearing the memory can be considered “good” only for cases when it is known that the type of the array has an initial state, which can be represented by all zero and for which the default constructor does not perform any actions.

This is generally true for built-in types, but also for other types.

The safest way is to set the elements to a default initialized temporary.

 template<class T, size_t N> void reset(T* v) { for(size_t i=0; i<N; ++i) v[i] = T(); } 

Note that if T is char , this function instantiates and converts exactly like memset . Thus, this is the same speed, nothing more.

+4
source

It is impossible to find out because it is a specific implementation. In general, memset will be the fastest because the library developers spent a lot of time optimizing it to be very fast, and sometimes the compiler can do optimizations on it, which cannot be done in manual implementations because it knows the value of memset .

+3
source

All Articles