堆栈在循环中分配 [英] Stack allocation inside a loop

查看:173
本文介绍了堆栈在循环中分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,当你写code是这样的:

In C, when you write code like this:

void some_function(void) {
    while (something) {
        char buf[4096];
        ...
    }
}

是否 BUF 的分配发生时被调用的函数?还是一个独立的分配发生了循环的每次迭代?

Does the allocation of buf happen when the function is called? Or does a separate allocation happen for every iteration of the loop?

会不会有,如果我把 BUF 的声明外(即在该函数的开头)?

Would there be any performance gain if I put the declaration of buf outside of the loop (i.e. at the beginning of the function)?

推荐答案

该BUF在some_function的堆栈帧分配。它只有当some_function被称为被分配一次。所以,即使你把BUF的声明之外,你不会得到任何的性能增益。

The buf is allocated in the frame of some_function on the stack. It only gets allocated once when some_function is called. So even if you put the declaration of buf outside, you won't get any performance gain.

但是,如果你写的东西就像是不同的。

But it's different if you write something like

while (...) {
  int a = 5;
}

中循环。分配情况每次迭代。

in the loop. The assignment happens each iteration.

这篇关于堆栈在循环中分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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