Kobi Burnley
Kobi Burnley

Reputation: 107

Initializing array in C - execution time

int a[5] = {0}; 

VS

typedef struct 
{ 
 int a[5]; 
} ArrStruct; 
ArrStruct arrStruct; 
sizeA = sizeof(arrStruct.a)/sizeof(int);
for (it = 0 ; it < sizeA ; ++it) 
    arrStruct.a[it] = 0; 

Does initializing by for loop takes more execution time? if so, why?

Upvotes: 0

Views: 246

Answers (2)

Floris
Floris

Reputation: 46365

It depends on the scope of the variables. For a static or global variable, the first initialization

int a[5]={0};

may be done at compile time, while the loop is run at, well, run time. Thus there is no "execution" associated with the former.

You may find the discussion of this question (and in particular this answer ) interesting.

Upvotes: 1

It depends upon the compiler and the optimization flags.

On recent GCC (e.g. 4.8 or 4.9) with gcc -O3 (or probably even -O1 or -O2) it should not matter, since the same code would be emitted (GCC has even an optimization which would transform your loop into a builtin_memset which would be further optimized).

On some compilers, it could happen that the int a[5] = {0}; might be faster, because the compiler might emit e.g. vector instruction (or on x86 a rep stosw) to clear an array.

The best thing is to examine the generated (gimple representation and) assembler code (e.g. with gcc -fdump-tree-gimple -O3 -fverbose-asm -mtune=native -S) and to benchmark. Most of the cases it does not matter. Be sure to enable optimizations when compiling.

Generally, don't care about such micro-optimization; a good optimizing compiler is better than you have time to code.

Upvotes: 2

Related Questions