函数内的局部变量何时*实际上*被分配 [英] When does a local variable inside a function *actually* gets allocated

查看:99
本文介绍了函数内的局部变量何时*实际上*被分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此感到好奇.以下是同一功能的两个代码段:

Just curious about this. Following are two code snippets for the same function:

void MyFunc1()
{
    int i = 10;
    object obj = null;

    if(something) return;
}

另一个是...

void MyFunc1()
{
    if(something) return;

    int i = 10;
    object obj = null;
}

现在第二个好处是当 something 为true时不分配变量吗?还是总是在调用函数后立即分配局部堆栈变量(在当前范围内),并且将return语句移到顶部没有效果?

Now does the second one has the benefit of NOT allocating the variables when something is true? OR the local stack variables (in current scope) are always allocated as soon as the function is called and moving the return statement to the top has no effect?

指向dotnetperls.com文章的链接当您在自己的计算机中调用方法时在C#程序中,运行时分配了一个单独的内存区域来存储所有本地变量插槽.即使您未在函数调用中访问变量,该内存也会分配在堆栈上."

已更新
这是这两个功能的IL代码的比较. Func2是指第二个片段.似乎这两种情况下的变量都是在开始时分配的,尽管在Func2()情况下,它们是在以后初始化的.所以我猜没有任何好处.

UPDATED
Here is a comparison of the IL code for these two functions. Func2 refers to second snipped. It seems like the variable in both the cases are allocated at the beginning, though in case of Func2() they are initialized later on. So no benefit as such I guess.

推荐答案

唯一可以确定何时发生这种情况的方法对于您的程序在运行时,是要查看JIT编译器在运行程序时发出的代码 .我们谁都没有权限甚至可以回答特定的问题(嗯,我想写CLR的人可以,只要他们知道您使用的是哪个版本的CLR,以及有关配置和实际程序代码的其他详细信息).

The only way to know for sure when this happens for your program, when you run it, is to look at the code the JIT compiler emits when you run your program. None of us can even answer the specific question with authority (well, I guess someone who wrote the CLR could, provided they knew which version of the CLR you're using, and possible some other details about configuration and your actual program code).

在本地变量堆栈上的任何分配严格来说都是实现细节".而且CLS不会保证我们会执行任何特定的操作.

Any allocation on the stack of a local variable is strictly "implementation detail". And the CLS doesn't promise us any specific implementation.

某些本地人从不本身通常会堆积在堆栈上,通常是由于存储在寄存器中,但是运行时改为使用堆空间是合法的,只要它可以保留堆空间即可.本地变量的正常生命周期语义.

Some locals never wind up on the stack per se, normally due to being stored in a register, but it would be legal for the runtime to use heap space instead, as long as it preserves the normal lifetime semantics of a local vaiable.

另请参阅埃里克·利珀特(Eric Lippert)的精彩系列堆栈是实现细节

See also Eric Lippert's excellent series The Stack Is An Implementation Detail

这篇关于函数内的局部变量何时*实际上*被分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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