Ugh. I see a lot of speculation going on. Let's see:
First of all, ask yourself: does performance even matter? IOW,
- have you benchmarked your program?
- did it turn out to be slow because of calling memset or the initialization?
- did changing it to the other alternative result in significant performance improvement?
I would guess that you haven't benchmarked it yet, in which case you definitely should. Or maybe performance is not really important here, in which case you should go with the stylistically superior one.
In general, however, there are a few things that can be said about this code. Note that this is all speculation, since I don't know what you are doing in the loop and thus can't reproduce your code and benchmark it, but I would.
First of all, I prefer the second version because it minimizes the scope of the buffer. Generally, you want to minimize the lifetime of variables so as to:
- minimize the probability of variable name collisions or accidentally re-using variables, and
- let the compiler's optimizer re-use their storage for other variables in order to minimize stack usage.
Additionally, today's aggressively-optimizing compilers will most probably treat both pieces of code identically. memset() is usually a compiler intrinsic function, so the compiler knows its semantics (i. e. that it fills memory with bytes). So, the compiler may inline the call to memset() and just emit code that zeroes out the memory if it turns out to be faster to do so, so there's no function call overhead.
The inverse decision can be made too: if the compiler deduces that it's better for some reason (i. e. reduced code size) to call a function, then it can substitute the byte-by-byte zero-initialization of the array to a call of memset(), and often it does indeed.
The argument I've read in some answers/comments that "initializing the array is more costly than resetting memory location" is simply nonsense -- I don't even understand what is meant by "resetting memory location". Both zero-initialization and memcpy(0) do the very same thing in this scenario, and chances are, if you compile with enough optimizations enabled, they will compile to the exact same machine code.
one.cis better choice. there same variable memory is set and unset but in case oftwo.cyou are creatinglooptimebuftwo.c.memsetis not magic. It has to go over all the memory that you want to zero. Semantically, it's equivalent with the re-initialization. (It's possible that the re-initialization is implemented by the compiler asmemsetor vice-versa). Your "nitialize the array in each iteration which is more costly then resetting memory location" simply makes no sense at all.one.c, there is an extra 4 KiB memory initialization. If the variable was not explicitly initialized inone.c, then the two would be equivalent.