简体   繁体   English

将现有阵列归零的最快方法是什么?

[英]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.

相关问题 将C int数组重置为零:最快的方法? - Reset C int array to zero : the fastest way? 从C ++中的字节数组中提取非零索引的最快方法是什么 - What's the fastest way to extract non-zero indices from a byte array in C++ 检查字符串数组中是否存在字符串的最快方法是什么? - What is the fastest way to check if a string is present in a string array? 将无符号字符数组转换为 IP 字符串的最快方法是什么 - What is the fastest way to convert unsigned char array to IP string 查看数组是否有两个共同元素的最快方法是什么? - What is the fastest way to see if an array has two common elements? 检查 char 数组中的前导字符的最快方法是什么? - What is the fastest way to check the leading characters in a char array? 将QImage的像素复制到数组的最快方法是什么? - What is the fastest way to copy a QImage's pixels to an array? 在opencv中使用imshow显示字节数组的最快方法是什么? - What is the fastest way to display a byte array using imshow in opencv? 在不排序的情况下搜索数组中重复项的最快方法是什么? - What's the fastest way to search for duplicates in an array without sorting it? 从排序的数字数组中返回一系列数字的最快方法是什么? - What is the fastest way to return a range of numbers from a sorted array of numbers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM