有两种方法可以将整数/ float 组清零:
memset(array, 0, sizeof(int)*arraysize);
或:
for (int i=0; i <arraysize; ++i)
array[i]=0;
显然,memset 对于大的arraysize
更快。然而,什么时候 memset 的开销实际上大于 for 循环的开销?例如,对于大小为 5 的数组——哪个最好?第一个、第二个,甚至可能是未滚动的版本:
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;
array[4] = 0;
最佳答案
很有可能,memset() 将被您的编译器内联(大多数编译器将其视为“内部”,这基本上意味着它是内联的,除非可能处于最低优化或除非明确禁用)。
例如,这里有一些release notes from GCC 4.3 :
Code generation of block move (
memcpy
) and block set (memset
) was rewritten. GCC can now pick the best algorithm (loop, unrolled loop, instruction with rep prefix or a library call) based on the size of the block being copied and the CPU being optimized for. A new option-minline-stringops-dynamically
has been added. With this option string operations of unknown size are expanded such that small blocks are copied by in-line code, while for large blocks a library call is used. This results in faster code than-minline-all-stringops
when the library implementation is capable of using cache hierarchy hints. The heuristic choosing the particular algorithm can be overwritten via-mstringop-strategy
. Newly alsomemset
of values different from 0 is inlined.
编译器可能会对您提供的替代示例做类似的事情,但我敢打赌它不太可能。
而且它是 grep
的,一眼就能看出启动的意图(并不是说循环特别难以理解)。
关于清除一个小整数数组 : memset vs. for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134103/