user997112
user997112

Reputation: 30615

Does the static keyword give any performance increase?

I appreciate that this is a micro-optimization, but I am interested in whether declaring either a function or member variable as static provides any performance increase compared to a non-static implementation?

I remember reading that const can be used for compilers to optimize, so it made me wonder whether static had any similar advantages.

Upvotes: 1

Views: 269

Answers (3)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

@DeadMG already pointed out that changing a member variable to static would completely change the semantics, the same applies to a static function.

In general the answer is no, static doesn't help performance (and neither does const) but one way that static can help is in an ELF shared library, where a static function isn't externally visible and so calls to it don't need to go through the procedure linkage table, which gives a small performance benefit which can be worth considering when writing code for shared libraries.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

Considering that static and non-static variables have extremely different semantics, whether or not you can declare static really has nothing to do with performance.

Also, cache and other issues might well mean "no".

Upvotes: 7

justin
justin

Reputation: 104698

it could be for data, if construction takes a long time (e.g. a precomputed buffer or something read from disk). often, this is only ideal when the data is immutable.

Upvotes: 1

Related Questions