如果我在声明之前返回

如果我在声明之前返回

本文介绍了如果我在声明之前返回,是否在堆栈上分配变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数,其粗略结构如下:

  int aRecursiveFunction(const SomeLargeStructure * a,int x) {
if(end recursion)
return 0;
// ...
if(大部分是真的)
return aRecursiveFunction(a,x + 1)+1;
// ...
SomeLargeStructure copy = * a;
alter(& copy);
return aRecursiveFunction(& copy,x);
}



我需要知道的是,出于性能原因, code> copy (这是一个大结构)将在90%的情况下创建在堆栈上的函数在此点之前结束的情况下。或者它实际上甚至不重要?它依赖于编译器吗?



EDIT

>:要澄清, sizeof(SomeLargeStructure)大约是500,它只有基本类型和数组(没有特殊的构造函数或赋值运算符等)。



EDIT 2 :好的,结论似乎是堆栈空间可能会每次都分配,但不会影响性能。在大多数平台上,可能需要的最大堆栈空间是可用的最大堆栈空间。在这种情况下,堆栈溢出并不是一个问题,因此关闭了大小写。

解决方案

分配在函数入口。但是通常分配堆栈空间只是加法,所以分配的空间量对性能没有影响。



你的问题读起来像是过早优化给我。这不是一个算法问题,您没有衡量性能问题。那么为什么你甚至考虑微优化?


Assume i have a function whose rough structure looks like this:

int aRecursiveFunction(const SomeLargeStructure *a, int x) {
    if (end recursion)
        return 0;
    // ...
    if (something that is mostly true)
        return aRecursiveFunction(a, x+1)+1;
    // ...
    SomeLargeStructure copy = *a;
    alter(&copy);
    return aRecursiveFunction(&copy, x);
}

What i need to know is, for performance reasons, whether the space for copy (which is a large structure) will be created on the stack in the 90 % of cases where the function ends before this point. Or does it actually not even matter? Does it depend on the compiler? Is it better to separate this part as another function?

Thanks.

EDIT: To clarify, sizeof(SomeLargeStructure) is around 500, it only has basic types and arrays (no special constructors or assignment operators etc.).

EDIT 2: Alright, the conclusion seems to be that the stack space probably will be allocated every time but it doesn't impact performance. Stack overflow is not an issue here, so case closed.

解决方案

On most platforms, the maximum stack space that might be needed is allocated on function entry. But usually allocating stack space is just addition, so the amount of space allocated has no effect on performance.

Your question reads like premature optimization to me though. This isn't an algorithmic issue and you don't have a measured performance issue. So why are you even thinking about micro-optimizations?

这篇关于如果我在声明之前返回,是否在堆栈上分配变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:23