Reputation: 7994
is there a performance difference between doing something like:
void function() {
char bufgfer[256];
// ...
}
and
void function() {
static char bufgfer[256];
// ...
}
I know it changed the way the function will work, but how about the performance? is the second one faster?
hanks
Upvotes: 1
Views: 253
Reputation: 215193
Never choose the storage duration (static vs automatic) of an object based on performance. Storage durations do not exist for performance purposes but because they have seriously different semantics; making the buffer static will horribly break lots of potential uses of your code, most obviously multi-threaded use. The only time an object should have static storage duration is when it's storing a long-term global state that needs to persist between invocations, and even then it's usually a design mistake (this state should be kept in a context held by the caller).
With that said, performance is unlikely to be better with static storage duration, and in many cases (especially PIC shared libraries or PIE executables) accessing a static variable will be slower than accessing an auto one, because the function must load the GOT register (if it's not already loaded) and do GOT-indirect or GOT-relative addressing.
Upvotes: 3
Reputation: 137282
It might be sometimes, and sometimes it might be slower, it depends on other variables in the function, and what does is access.
The most important thing is using it when needed, and not in terms of optimizations, but in term of functionality. If you don't need a variable to be static, it shouldn't be, the implications on different platforms are irrelevant most of the time.
Upvotes: 2
Reputation: 72312
The first one is probably faster if the buffer ends up in a cache near the CPU.
If you thought that the first one was slower because the buffer would somehow be allocated at run time, then, no, this is not the reason. All this is handled by the compiler at compile time. Moreover, making the buffer static will probably keep it out of the cache. (But who knows, or cares?)
It seems to me that you're considering premature optimizations.
Upvotes: 3