Question

Ingredients:

  • two languages -- like C++ and C#
  • a type way more complex than just a Point with two members (fields x and y)

In C# such type would be defined as reference type forcing it to allocate it always on heap. In C++ allocation is defined by usage, not by type definition thus it is possible to allocate it on stack.

The benefit of this is RAII pattern, with the effect of automatically cleaning the data after object goes out of scope. In C# you have to use using as explicit "cleaning-scope" (it is also due to nondeterministic GC).

The second I know is speed -- stack access is faster.

My question is this -- is there any (naming one is sufficient) other real benefit (except RAII and speed) of ability to allocate complex object on stack (like in C++) in comparison to always on heap (as in C#)?

Real -- preferable, I am looking for something which is unavailable for "always on heap" approach, because RAII is resolved after all with different syntax.

This question does not involve value types (structs) in C#! It is cross-language comparison.

Was it helpful?

Solution

is there any (naming one is sufficient) other real benefit except RAII and speed of ability to allocate complex object on stack

Yes, and this one is much more important than speed of allocation: speed of access. You can get dramatic performance improvements by getting rid of unnecessary indirections. Herb Sutter gave an interesting talk recently which, among other things, covers his strong love for contiguous memory. An example project he cites got a 50x performance improvement by making life easier for the prefetcher. (Yes, we ware talking about 50 times faster, not 50 percent faster!)

OTHER TIPS

This is not the real answer to your question, but it's longer than it fits into a comment.

It is a misconception that in C# value types are allocated on the stack and reference types are allocated on the heap. Value types are not defined as something that goes on the stack. That is an implementation detail and not a design specification. The specification is that value types are copied by value. That does not mean they must be stored on the stack. It's possible to implement a C# compiler that doesn't use the stack at all. Instances of value or references types go to the stack, heap or registers depending whether they are short-lived or long-lived. Examples of value types that are not stored on the stack are

  • Fields in a class
  • Boxed value types
  • Outer variables of anonymous methods
  • Outer variables of iterator blocks

Fore more information I suggest reading Eric Lippert's posts on the matter:

One benefit of the stack model versus heap+GC is that it's more deterministic. Certainly in real-time systems it is useful to measure how long a function takes, and that's hard when some of the cleanup costs are incurred at an unspecified later time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top