lovelace0207
lovelace0207

Reputation: 1

Does initializing arrays have a significant effect on C++ performance?

I am trying to decompose a 4000+ line block of legacy C++ code into separate functions. At the beginning of the function, a lot of char arrays are declared. The same arrays are used in completely different ways as buffers for data, for example:

char array[4];
strcpy(array, "foo");
//something with foo
strcpy(array, "bar");
//something with bar

I want to separate these into

void foo() {
    char foo[4];
    strcpy(foo, "foo");
    //something with foo
}

void bar() {
    char bar[4];
    strcpy(bar, "bar");
    //something with bar
}

However performance is important here, and I'm wondering if initialising many more arrays is likely to negatively impact speed. (Obviously I'm not going to paste 4000 lines of code).

Upvotes: 0

Views: 284

Answers (1)

eerorika
eerorika

Reputation: 238311

Does initializing arrays have a significant effect on C++ performance?

One cannot make universal generalisations that would apply to all programs. But in case of small arrays: Initialisation rarely has significant cost. You can find whether the cost is significant in your program by measuring.

Default-initialising an array of trivial objects - such as in your example - has (typically) no overhead at all.

Upvotes: 1

Related Questions