简体   繁体   English

函数局部静态变量:从性能角度的优缺点

[英]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!非常感谢您的帮助!

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.正如评论所指出的@Aconcagua,如果辅助(未返回)的本地对象是昂贵的初始化或使用,使其static和重复使用,否则可能导致显著加速。 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).当然,如果可以通过这种方式创建非常大的向量/字符串,则应该意识到这种方法可能会显着增加进程 RSS(映射到 RAM 的内存量)。

In multi-threaded applications, we just use thread_local instead of static .在多线程应用程序中,我们只使用thread_local而不是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.另一方面,对于基本类型的小对象(例如示例代码中的整数或指针),我敢说将它们设为static可能会导致更多的内存访问。 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 .对于静态变量,它们的值必须在函数调用之间保留,这很可能导致它们存储在内存中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM