N
Nick Hounsome
Mike said:Not necessarily. Assuming your entity lifetime matches the defining scope
of the stack var, this may be true - but otherwise often not.
That's why many C++ programs that are improperly using value semantics run
much faster when ported to C# -
it avoids the invocation of copy constunctors, etc., every time an
instance is passed on the stack.
Sure, this may not be a properly designed program, but it not always easy
to see where this is going to happen in complex code.
This is a discussion of C# not C++.
The lifetime of an entity on the stack ALWAYS matches the defining scope. If
the entity is a reference then the lifetime of the reference matches the
defining scope even if the lifetime of the object referenced doesn't.
Stack is faster because at the end of a method it is always valid to just
alter the stackpointer by the number of bytes allocated on the stack or more
typically to load the previous frame's stack pointer. NB structs are
prohibitted from having destructors precisely because it would prevent this
use of stacks [they would have to be called exectly like C++ destructors -
It could obviously be done and it would create some interesting new
programming opportunities! Perhaps 3.0?]
In C# there is less performance benefit on allocation (as opposed to C++)
because C# just increases a pointer and leaves all the hard work to garbage
collection though even here stack is still sloghtly cheaper because there is
no locking involved as the stack is inherently local to the thread.