静态局部变量可以减少内存分配时间吗? [英] Can static local variables cut down on memory allocation time?

查看:88
本文介绍了静态局部变量可以减少内存分配时间吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在单线程程序中有一个像这样的函数

Suppose I have a function in a single threaded program that looks like this

void f(some arguments){
    char buffer[32];
    some operations on buffer;
}

和f出现在某个经常被调用的循环中,所以我想使其尽可能快.在我看来,每次调用f时都需要分配缓冲区,但是如果我声明它是静态的,则不会发生.那是正确的推理吗?这是免费的吗?正是由于这个事实(很容易加快速度),优化的编译器是否已经对我做了类似的事情?

and f appears inside some loop that gets called often, so I'd like to make it as fast as possible. It looks to me like the buffer needs to get allocated every time f is called, but if I declare it to be static, this wouldn't happen. Is that correct reasoning? Is that a free speed up? And just because of that fact (that it's an easy speed up), does an optimizing compiler already do something like this for me?

推荐答案

对于使用堆栈作为局部变量的实现,通常情况下,分配涉及到推进寄存器(向其添加值),例如堆栈指针(SP).登记.这个时间可以忽略不计,通常只有一条指令或更少的指令.

For implementations that use a stack for local variables, often times allocation involves advancing a register (adding a value to it), such as the Stack Pointer (SP) register. This timing is very negligible, usually one instruction or less.

但是,堆栈变量的初始化花费的时间稍长一些,但是又很少.查看您的汇编语言列表(由编译器或调试器生成)以获取详细信息.标准中没有关于初始化变量所需的持续时间或指令数量的任何规定.

However, initialization of stack variables takes a little longer, but again, not much. Check out your assembly language listing (generated by compiler or debugger) for exact details. There is nothing in the standard about the duration or number of instructions required to initialize variables.

静态局部变量的分配通常以不同的方式处理.一种常见的方法是将这些变量与全局变量放在同一区域.通常,此区域中的所有变量都在调用main()之前初始化.在这种情况下,分配是将地址分配给寄存器或将区域信息存储在内存中的问题.这里没有浪费太多的执行时间.

Allocation of static local variables is usually treated differently. A common approach is to place these variables in the same area as global variables. Usually all the variables in this area are initialized before calling main(). Allocation in this case is a matter of assigning addresses to registers or storing the area information in memory. Not much execution time wasted here.

动态分配是燃烧执行周期的情况.但这不在您的问题范围内.

Dynamic allocation is the case where execution cycles are burned. But that is not in the scope of your question.

这篇关于静态局部变量可以减少内存分配时间吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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