memset
(from <string.h>
) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand.
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
By the way, in C++ the idiomatic way would be to use std::fill
(from <algorithm>
):
std::fill(myarray, myarray+N, 0);
which may be optimized automatically into a memset
; I'm quite sure that it will work as fast as memset
for int
s, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…