memset
September 7, 2009
I haven’t used this much, but I’ve been working on modding a program in C which does. At first I didn’t quite get what it was up to, and since I like to know both the why and how, I did some digging. The result? I found a very interesting performance boost for using memset to initialize arrays, as well as a simple one liner.. (which is what the program has been using it for). The ‘ ‘ in the code is really ‘ \ 0 ‘ (no spaces)
example: these are equivalent
const ARRAY_LEN;
my_array[ARRAY_LEN];
unsigned int i;
for(i=0; i < ARRAY_LEN; i++)
{
my_array[i] = '';
}
and
memset(&my_array, '', sizeof(my_array));
And it gets better..
The table below compares two different methods for initializing an array of characters: a for-loop versus memset(). As the size of the data being initialized increases, memset() clearly gets the job done much more quickly:
| Input size | Initialized with a for-loop | Initialized with memset() |
|---|---|---|
| 1000 | 0.016 | 0.017 |
| 10000 | 0.055 | 0.013 |
| 100000 | 0.443 | 0.029 |
| 1000000 | 4.337 | 0.291 |
sources: http://www.cppreference.com/wiki/c/string/memset