对静态函数变量的访问是否比对全局变量的访问慢? [英] Is access to a static function variable slower than access to a global variable?

查看:115
本文介绍了对静态函数变量的访问是否比对全局变量的访问慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态局部变量在第一个函数调用上初始化:

Static local variables are initialised on the first function call:

在块范围内使用说明符static声明的变量具有静态存储持续时间,但在控件第一次通过其声明时进行初始化(除非其初始化为零或常量初始化,这可以在首次进入该块之前执行) .在所有其他调用上,将跳过声明.

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

此外,在C ++ 11中,还有更多检查:

Also, in C++11 there are even more checks:

如果多个线程尝试同时初始化同一静态局部变量,则初始化仅发生一次(可以使用std :: call_once获得任意函数相似的行为). 注意:此功能的通常实现使用双重检查锁定模式的变体,从而将已经初始化的局部静态数据的运行时开销减少到单个非原子布尔比较. (自C ++ 11起)

If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with std::call_once). Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison. (since C++11)

同时,全局变量似乎在程序启动时进行了初始化(尽管从技术上讲,cppreference中只提到了分配/解除分配):

At the same time, global variables seem to be initialised on program start (though technically only allocation/deallocation is mentioned on cppreference):

静态存储持续时间.在程序开始时分配对象的存储空间,在程序结束时释放对象的存储空间.该对象只有一个实例.在名称空间范围内声明的所有对象(包括全局名称空间)都具有此存储期限,以及使用静态或外部声明的对象.

static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern.

因此,给出以下示例:

struct A {
    // complex type...
};
const A& f()
{
    static A local{};
    return local;
}

A global{};
const A& g()
{
    return global;
}

am我正确地假设f()必须在每次调用它时都要检查其变量是否已初始化,因此f()将比g()慢?

am I correct to assume that f() has to check whether its variable was initialised every time it is called and thus f() will be slower than g()?

推荐答案

您当然在概念上是正确的,但是当代建筑可以解决这个问题.

You are conceptually correct of course, but contemporary architectures can deal with this.

现代的编译器和体系结构将安排管道,以便采用已经初始化的分支.因此,初始化的开销将导致额外的管道转储,仅此而已.

A modern compiler and architecture would arrange the pipeline such that the already-initialised branch was assumed. The overhead of initialisation would therefore incur an extra pipeline dump, that's all.

如果有任何疑问,请检查组装.

If you're in any doubt, check the assembly.

这篇关于对静态函数变量的访问是否比对全局变量的访问慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆