简体   繁体   中英

What is the fastest way to zero an existing array?

我有一个现有的1D阵列,是memset以零的最快方式吗?

Fastest ... probably yes. Buggy almost sure!

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

In C++ when a variable is defined its constructor is called. When an array is defined, all the array's elements' constructors are called.

Wiping out the memory can be considered "good" only for the cases when the array type is know to have an initial state that can be represented by all zero and for which the default constructor doesn't perform any action.

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

The safest way is to assign the elements with 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 , the function instantiates and translates exactly as memset . So it is the same speed, no more no less.

This is impossible to know because it's implementation specific. Generally though, memset will be the fastest because the library implementers have spent a lot of time optimising it to be very fast, and sometimes the compiler can do optimisations on it that can't be done on hand-rolled implementations because it knows the meaning of memset .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM