Reset C int array to zero : the fastest way?

前端 未结 7 1336
感情败类
感情败类 2020-12-22 18:34

Assuming that we have a T myarray[100] with T = int, unsigned int, long long int or unsigned long long int, what is the fastest way to reset all its content to

7条回答
  •  星月不相逢
    2020-12-22 18:51

    memset (from ) 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 ):

    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 ints, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.

提交回复
热议问题