The structure of stack storage. #82319
-
I am just curious about how the stack is managed when we see inline variable declarations in C#, consider: static void Main(string[] args)
{
int outer;
if (args.Length > 0)
{
int inner;
if (args[0] != null)
{
int deeper;
// do stuff
}
}
} Does the function have a single fixed size stack frame that can store potentially every variables that could be active, or does it create additional frames as each declaring block is entered as execution progresses? I did try to search for information online but it's hard to know how to phrase the question! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
A lot of this will come down to the JIT, but I'm pretty sure all the stack space for the call is reserved up-front, though space might be reused for non-overlapping variables. |
Beta Was this translation helpful? Give feedback.
-
IL has no scoping of locals, they are all declared up front:
There can be a 1-to-1 mapping of C# locals to IL locals, although the compiler can decide to reuse local slots if it wants to. |
Beta Was this translation helpful? Give feedback.
-
Thanks, so this is likely faster than trying to minimize the stack usage by only allocating stack space as needed and releasing that as blocks are exited. So there's no real runtime cost to these, I mean when each declaration is encountered (as we mentally look at the code) nothing happens, it has all been done already as soon as the function was started? |
Beta Was this translation helpful? Give feedback.
-
Moving to runtime as this is ultimately not a question/concern for the language. This is a space where the answer can be 'it depends' as impls are free to do what they want as long as they abide by the semantics of their respective specifications. For example, IL might require locals to be specified in a certain format. But the JIT may be free to execute however it wants at runtime as long as what it does is not observable. Similarly, there's no requirement from the language level that "C# locals" even translate to IL locals. So questions on this are better answered by respective impl teams, vs language. Thanks. |
Beta Was this translation helpful? Give feedback.
IL has no scoping of locals, they are all declared up front:
There can be a 1-to-1 mapping of C# locals to IL locals, although the compiler can decide to reuse local slots if it wants to.