Dor
Dor

Reputation: 7504

Local function variables initialization takes processing time?

Local function variables initialization takes processing time? e.g.:

void foo ( void ) {
    char *str = "hello";
    int num = 3;
}

Or, like global variables, their value is assigned already in the read-only section of the binary?

In other words: Would it be time-consuming to invoke a function that has many local variables, comparing to a function that has none?

Edit: I see many people here are angry because that it seems that I'm trying to optimize my code in a very picky/bad way, which shouldn't be considered. I'm aware of this. I asked this question only to understand how things behave and function, not for optimization reasons. Thank you. BTW, perhaps my codes sits on a low-power MCU? Consider other options, PC isn't the only one.

Upvotes: 1

Views: 439

Answers (2)

Sam Post
Sam Post

Reputation: 3821

If you're feeling adventurous, try dissasembling your executable with objdump with and without extra variables. You'll see that there are extra instructions inserted by the compiler (either setting a register or doing a load operation) when you create more local variables in your function. Every instruction takes nonzero time...

Upvotes: 0

John Knoeller
John Knoeller

Reputation: 34218

It's not a lot of time, but yes. it takes time.

In this example the text "hello" would already live somewhere as a constant value, but str would have to be set to point to it at runtime.

and the value 3 would have to be stored in num

Upvotes: 3

Related Questions