问题
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