is memset more efficient than for loop. so if i have
char x[500];
memset(x,0,sizeof(x));
or
char x[500];
for(int i = 0 ; i &
The answer is 'it depends'. memset
MAY be more efficient, or it may internally use a for loop. I can't think of a case where memset
will be less efficient. In this case, it may turn into a more efficient for loop: your loop iterates 500 times setting a bytes worth of the array to 0 every time. On a 64 bit machine, you could loop through, setting 8 bytes (a long long) at a time, which would be almost 8 times quicker, and just dealing with the remaining 4 bytes (500%8) at the end.
EDIT:
in fact, this is what memset
does in glibc:
http://repo.or.cz/w/glibc.git/blob/HEAD:/string/memset.c
As Michael pointed out, in certain cases (where the array length is known at compile time), the C compiler can inline memset
, getting rid of the overhead of the function call. Glibc also has assembly optimized versions of memset
for most major platforms, like amd64:
http://repo.or.cz/w/glibc.git/blob/HEAD:/sysdeps/x86_64/memset.S