[英]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. 在C ++中定义变量时,会调用其构造函数。 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
. 请注意,如果T为
char
,则函数将实例化并完全转换为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
. 一般来说,
memset
将是最快的,因为库实现者花费了大量时间来优化它非常快,有时编译器可以对它进行优化,这是在手动实现上无法完成的,因为它知道其含义 memset
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.