I have an array of int and i have to initialize this array with the value -1. For now i use this loop:
int i;
int myArray[10];
for(i = 0; i < 10; i++)
myArray[i] = -1;
There are faster ways?
The quickest way I know for the value -1 (or 0) is memset:
int v[10];
memset(v, -1, 10 * sizeof(int));
Anyway you can optimize the loop in this way:
int i;
for(i = 10; i--;)
v[i] = -1;
If you want to initialize the array at the time of declaration with 0, you can use:
int a[10] = {0}; which is very fast. But if you want to initialize with some other value or want to re-initialize your array with 0 at some point later in the code, use:
memset(a, -1, size_a); (or memset(a, 0, size_a); respectively) or a loop. In my opinion, always prefer memset() to looping because memset() is often optimized to set entire words in memory to the initialization value given as its argument instead of setting individual bytes.
For stats, on my 32-bit Linux installation with 4GB memory and 2.2GHz*2 processor, the running times of four types of array initialization codes are given below:
1). 0.002s
#include <string.h>
#define SIZE 1000000
int a[SIZE];
int main(void)
{
return 0;
}
2). 0.008s
#include <string.h>
#define SIZE 1000000
int main(void)
{
int a[SIZE] = {0};
return 0;
}
3). 0.003s
#include <string.h>
#define SIZE 1000000
int main(void)
{
int a[SIZE];
memset(a, -1, SIZE);
return 0;
}
4). 0.011s
#include <string.h>
#define SIZE 1000000
int main(void)
{
int a[SIZE];
int i;
for(i = 0; i < SIZE; i++)
a[i] = -1;
return 0;
}
memset by any sane optimizing compiler.-O2 or with -O3, gcc 4.5.2 does optimize the allocation loop to memset()-like assembly code.In GNU C what you can do is:
int myArray[10] = {[0 ... 9] = -1};
Initializing a range of elements: http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
And as nobody mentioned it, in portable C:
int myArray[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};