What is the fastest way to zero an existing array?

别说谁变了你拦得住时间么 提交于 2019-12-10 18:44:07

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8717640/what-is-the-fastest-way-to-zero-an-existing-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!