Quick method to initialize an array

I have an array from int, and I have to initialize this array with a value of -1. While I use this loop:

int i;
int myArray[10];

for(i = 0; i < 10; i++)
    myArray[i] = -1;

Are there any faster ways?

+5
source share
4 answers

The fastest way I know for value -1(or 0), memset :

int v[10];
memset(v, -1, 10 * sizeof(int));

In any case, you can optimize the loop this way:

int i;
for(i = 10; i--;)
    v[i] = -1;
+5
source

0, : int a[10] = {0};, . - 0 - , : memset(a, -1, size_a); ( memset(a, 0, size_a); ) . -, memset() , memset() , , .

, 32- Linux 4-- 2,2 * 2, :

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;
}
+5

GNU C :

int myArray[10] = {[0 ... 9] = -1};

: http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

, C:

int myArray[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
+2
source

memset very fast.

int arr[10];
memset(arr, -1, sizeof(arr));

However, what you have will most likely turn into a memset call by the optimizing compiler. Look at the assembly to make sure, but it is unlikely that the loop will remain a loop during compilation.

+1
source

All Articles