S.V
S.V

Reputation: 2793

Function local static variables: pros/cons from performance point of view

What are the pros/cons of function local static variables purely from performance point of view?

Here is an example:

// version 1
void func(/*some arguments here*/)
{
 int64_t x;
 int32_t y = 0;
 void * p = 0;
 // do something here
}

// version 2
void func(/*some arguments here*/)
{
 static int64_t x;
 static int32_t y; y = 0;
 static void * p; p = 0;
 // do something here
}

Which version will be faster? Will it always be faster? In what situation one might shoot oneself in the foot by using static local variables for performance?

Thank you very much for your help!

Upvotes: 0

Views: 1065

Answers (1)

Daniel Langr
Daniel Langr

Reputation: 23527

This question is too broad to be generally answered. However, I would just share my experience with the development of some real-world applications. As pointed out by @Aconcagua in comments, if an auxiliary (not-returned) local object is expensive to initialize or use, making it static and reusing it might result in significant speedup. This happens in our cases especially with auxiliary local vectors, where reusing avoids heap allocations. Compare

void f() {
  std::vector<...> v;
  ...  // at least one allocation required in each call when inserting elements
}

with

void f() {
  static std::vector<...> v;
  v.clear();
  ...  // no allocation required if elements fit into capacity
}

The same applies to (non-small) strings. Of course, if very large vectors/strings may be created this way, one should be aware that this approach may considerably increase process RSS (amount of memory mapped to RAM).

In multi-threaded applications, we just use thread_local instead of static.


On the other hand, for small objects, basically of fundamental types (such as integers or pointers in your exemplary code), I would dare to say that making them static may result in more memory accesses. With non-static variables, they will be more likely mapped to registers only. With static variables, their values must be preserved between function calls, which will much likely result in their storage in memory.

Upvotes: 1

Related Questions