1

I've read countless articles where class and object instance variables are stored on the heap, while local and method variables generally are stored on the stack.

But what about method parameters that are objects?

private void myMethod (int a, myObject b)
{
   bool c = (a > 0 && b.myCounter < 0 ? true : false);
   //do some more work
}

//Are both a & b stored in the stack? Or is "a" in the stack and "b" on the heap?

EDIT/UPDATE: "b" is currently a class, not a struct. It has approximately 20 properties with some properties determined by a boolean operation of properties contained within it (similar to how "c" is done in the code example), so would consider refactoring it into a struct if that makes more sense.

Looking at such micro-optimizations as this is a real-time and resource-performance critical financial application.

  • int a will be stored on stack as it's a value type. i do not know what is the type of myObject which will be used to determine if it's stored on a stack or heap. rule of thumb is all reference types are stored on heap. – Baahubali Jul 24 '19 at 01:14
  • 1
    Implementation specific... including not using stack at all (also there are no known implementation that do so)… Probably duplicate of https://stackoverflow.com/questions/4487289/memory-allocation-stack-vs-heap (at very least worth reading to [edit] post to avoid "generally stored on the stack" generalizations and using proper terms for "local and method variables" - no idea what you mean as method variables here) – Alexei Levenkov Jul 24 '19 at 01:25
  • 1
    Going further, you shouldn't be worrying about the stack or heap in .Net unless you really have a need to do so, i.e micro optimisations in extreme time critical applications. Not only may this change for implementations to versions, its also can be very nuanced when which gets used . voting to close this as too broad. – TheGeneral Jul 24 '19 at 01:35
  • Assuming `myObject` is a class, then the object to which `b` refers is stored on the heap. However the values of both of the parameters `a` and `b` will be stored on the stack. The int is a value type, so its value will be copied from the call site into a stack slot before the function is called. The `b` parameter is a reference to a reference type instance. At the function call site, the value of the reference to that object will also be copied to a stack slot right before the call. – Flydog57 Jul 24 '19 at 04:04

1 Answers1

1

Is "b" a instance of a class or a instance of a struct?

  • If it's a instance of a class, in the stack there is a reference to the original data, and the original data is stored in the heap.
  • If it's a instance of a struct, it's stored in the stack.