假设我们有一个 T myarray[100]
,其中 T = int、unsigned int、long long int 或 unsigned long long int,那么将其所有内容重置为零的最快方法是什么(不仅用于初始化,而且在我的程序中多次重置内容)?也许用 memset?
对于像 T *myarray = new T[100]
这样的动态数组有同样的问题。
最佳答案
memset
(来自 <string.h>
)可能是最快的标准方法,因为它通常是直接用汇编编写并手动优化的例程。
memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays
memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements
顺便说一句,在 C++ 中,惯用的方法是使用 std::fill
(来自 <algorithm>
):
std::fill(myarray, myarray+N, 0);
其中可以自动优化为memset
;我很确定它会像 memset
一样快。对于 int
s,而如果优化器不够聪明,它对于较小的类型的性能可能会稍差一些。不过,如有疑问,请提供个人资料。
关于c++ - 将 C int 数组重置为零 : the fastest way?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9146395/