I have multiple same length arrays I wish to fill with zero's. Let's look at two ways of doing that:
1)
int i;
for(i=0;i<ARRAYSLENGTH;i++){
arr1[i]=0;
arr2[i]=0;
arr3[i]=0;
...
}
2) memset all the arrays to zero.
In a recent code review I was asked to change option 1 to option 2. Which made me wonder, Which of these methods is better ? Mainly:
Is 2 considered more readable than 1?
How do these two methods compare in terms of efficiency ? (considering memset is usually implemented in assembly but method 1 only increments the counter once for multiple arrays).
memsethas some tricks up its sleeve that can make it faster than the naive one-by-one approach.A arr1[10] ={0};It will set all the10elements to0.memsetor the simpler (IMO)A arr[NUM_ARRAYS][ARRAY_LENGTH] = {{0}};.memsetwill only work when initializing with a constant stream of bytes while the initialization syntax will only work when all unmentioned values are to be set to 0. If/When you want to initialize to something else, theforloop will be your best bet.forloops into calls tomemset, so there may be no performance advantage whatsoever. In that case you should prefer whichever version is clearer.