Is it faster to get the compiler to initialize the array or manually iterate over the array to initialize?

there is

int array[100] = {};

faster than

int array[100];
for(int i=0; i<100; ++i){
    array[i] = 0;
}

Or are they equal? What are the differences, if any?

+4
source share
4 answers

Initialization of non-statically distributed arrays may well be implemented identically for both options shown. You will need to measure or view the created assembly.

( ++), UNIX BSS . BSS , . , , . ( , , , , .)

, , (

+3

, , , . , . array , . , 0 , . .

, 0, , .

+1

:

int array[100] = {};

, , , . , , , . O (1), .

:

int array[100];
for(int i=0; i<100; ++i){
   array[i] = 0;
}

- O (N). , O (N), for. , , for, .

, , . for .

+1
int array[100] = {};

This will initialize the array by default - this means that for basic (scalar) types, the entire array will be correctly initialized to zero and indeed O (1) times. since its compiler implementation must be optimized.

int array[100];
for(int i=0; i<100; ++i){
    array[i] = 0;
}

here the programmer rises and takes responsibility for initializing the array. Now it depends on how well the compiler optimization code is written to answer the question of whether it matches the previous initialization or may not match.

+1
source

Source: https://habr.com/ru/post/1531110/


All Articles