what is the memory overhead on the stack and heap of A versus B
A:
private string TestA()
{
string a = _builder.Build();
return a;
}
B:
private string TestB()
{
return _builder.Build();
}
what is the memory overhead on the stack and heap of A versus B
A:
private string TestA()
{
string a = _builder.Build();
return a;
}
B:
private string TestB()
{
return _builder.Build();
}
They both get optimised to the same thing.
In answer to the question in your title "do all local variables go on the stack" the simple answer is not exactly. All objects get stored on the 'heap' (don't remember if that's what it's called in .NET) regardless. C# has a generational-based garbage collector that's aware that some objects only live a very short time and so is designed to manage this efficiently.
re the efficiency question; the two are identical, and in release mode will be reduced to the same thing. Either way, string
is a reference-type, so the string
itself is always on the heap. The only thing on the stack would be the reference to the string
- a few bytes (no matter the string length).
"do all local variables go on the stack": no; there are two exceptions:
yield return
etc)In both cases, there is a compiler generated class behind the scenes:
int i = 1;
Action action = delegate {i++;};
action();
Console.WriteLine(i);
is similar to:
class Foo {
public int i; // yes, a public field
public void SomeMethod() {i++;}
}
...
Foo foo = new Foo();
foo.i = 1;
Action action = foo.SomeMethod;
action();
Console.WriteLine(foo.i);
Hence i
is on an object, hence on the heap.
Iterator blocks work in a similar way, but with the state machine.