全局变量比C中的局部变量更快吗? [英] Are global variables faster than local variables in C?

查看:852
本文介绍了全局变量比C中的局部变量更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此有几点想法。首先是分配全局变量可能会更快,因为在程序第一次产生时它们只被分配一次,而在每次调用函数时必须分配局部变量。我的第二个想法是,由于局部变量在堆栈中,因此它们通过基址指针寄存器访问,所以每次访问局部变量时,存储在基址指针中的值都必须递减;全局变量通过数据段中的静态地址直接访问。我的想法是否准确?

解决方案

你研究计算机体系结构,你会发现最快的存储是寄存器,其次是缓存,其次是RAM。关于局部变量的事情是,如果可能的话,编译器优化它们从寄存器中分配,否则从缓存中分配。这就是为什么局部变量更快的原因。



对于嵌入式系统,确保可以编译成一个小内存模型,在这种情况下,您的数据段可能适合现代控制器的SRAM缓存。但是在这种情况下,你的本地变量的使用也会非常紧张,以至于它们可能完全在寄存器上运行。



结论:在大多数情况下,局部变量会更快比全局变量。


I had a couple thoughts on this. The first is that allocating global variables may be faster, since they are only allocated once, at the time the program is first spawned, whereas local variables must be allocated every time a function is called. My second thought is that since local variables are on the stack, they are accessed through the base pointer register, so the value stored in the base pointer must be decremented every time a local variable is accessed; global variables are accessed directly through their static addresses in the data segment. Is my thinking accurate?

解决方案

It's rather inaccurate.

If you study computer architecture, you'll find out that the fastest storage are the registers, followed by the caches, followed by the RAM. The thing about local variables is that the compiler optimizes them to be allocated from the registers if possible, or from the cache if not. This is why local variables are faster.

For embedded systems, sure it might be possible to compile to a tiny memory model in which case your data segment may possibly fit into a modern controller's SRAM cache. But in such cases, your local variable usage would also be very tight such that they are probably operating entirely on registers.

Conclusion: In most cases, local variables will be faster than global variables.

这篇关于全局变量比C中的局部变量更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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