Oren
Oren

Reputation: 4252

Memset or for loop to zero multiple same length arrays

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).

Upvotes: 0

Views: 376

Answers (3)

trax
trax

Reputation: 739

You can even use bzero instead of memset which is more specific

Upvotes: 0

michaelca
michaelca

Reputation: 131

I think most programmers should be able to read memset and know what it's doing so readability shouldn't be an issue. With most modern compilers you probably wouldn't see much performance difference but I would use memset as that's what it's for.

Upvotes: 0

abelenky
abelenky

Reputation: 64672

Your method 1 (the for loop), is bad for the cache.

As arr1, arr2, arr3 may not be anywhere near each other in memory, and very likely will not be in the cache together, you could have frequent cache-misses, and the CPU will have to constantly fetch new pieces from memory, just to set them to zero.

By doing a set of memset operations, you'll hit ALL of arr1, at once, almost certainly entirely from the cache. Then you'll cache and set all of arr2 very quickly, etc, etc.

That, and because memset may well have assembly tricks and optimizations to make it faster, I would definitely prefer option 2 over option 1.

Upvotes: 5

Related Questions