Mark Roworth
Mark Roworth

Reputation: 566

C# stack frames, curly brackets and performance

Do curly brackets always imply a stack frame. Example 1:

{
    int b;
}

Obviously a stack frame will be created. So then example 2:

<some code>
{
    int a;
    <some more code>
}
<yet more code>

I'd assume there will be a stack frame to reflect the scope of a.

Example 3:

for (i=0; i<10; i++)
{
    <single statement of code>
}

Is a stack frame created for the scope of i?

Example 4:

And is it more efficient code-wise to use:

for (i=0; i<10; i++)
    <single statement of code>

In generally, my question is does the compiler always create a stack frame when curly braces are used, or does it use intelligence and only create them when required?

[If my knowledge of stack frames seems a bit simplistic, I'm going back 30 years to my degrees, so apologies for that]

Upvotes: 0

Views: 188

Answers (1)

Enigmativity
Enigmativity

Reputation: 117114

When I write this:

int x = 4;
int y = 3;
Console.WriteLine(x + y);
Console.WriteLine(x);

Or this:

int x = 4;
{
    int y = 3;
    Console.WriteLine(x + y);
}
Console.WriteLine(x);

I still get this in the IL:

.maxstack 2
.locals init (
    [0] int32 x,
    [1] int32 y
)

There's not an extra stack frame.

Upvotes: 1

Related Questions