Heap versus Stack allocation implications (.NET)

130

Solution 1

So long as you know what the semantics are, the only consequences of stack vs heap are in terms of making sure you don't overflow the stack, and being aware that there's a cost associated with garbage collecting the heap.

For instance, the JIT could notice that a newly created object was never used outside the current method (the reference could never escape elsewhere) and allocate it on the stack. It doesn't do that at the moment, but it would be a legal thing to do.

Likewise the C# compiler could decide to allocate all local variables on the heap - the stack would just contain a reference to an instance of MyMethodLocalVariables and all variable access would be implemented via that. (In fact, variables captured by delegates or iterator blocks already have this sort of behaviour.)

Solution 2

(edit: My original answer contained the oversimplification "structs are allocated on the stack" and confused stack-vs-heap and value-vs-reference concerns a bit, because they are coupled in C#.)

Whether objects live on the stack or not is an implementation detail which is not very important. Jon has already explained this well. When choosing between using a class and struct, it is more important to realize that reference types work differently than value types. Take the following simple class as an example:

public class Foo
{
   public int X = 0;
}

Now consider the following code:

Foo foo = new Foo();
Foo foo2 = foo;
foo2.X = 1;

In this example, foo and foo2 are references to the same object. Setting X on foo2 will also affect foo1. If we change the Foo class to a struct then this is no longer the case. This is because structs are not accessed through references. Assigning foo2 will actually make a copy.

One of the reasons for putting stuff on the stack is that the garbage collector does not have to clean it up. You typically should not worry about such things; just use classes! Modern garbage collectors do a pretty good job. Some modern virtual machines (like java 1.6) can even determine whether it is safe to allocate objects on the stack even if they are not value types.

Solution 3

In .NET there's little to discuss as it is not the user of a type who decides where to allocate instances.

Reference types are always allocated on the heap. Value types are per default allocated on the stack. The exception is if the value type is part of a reference type in which case it is allocated on the heap along with the reference type. I.e. the designer of a type makes this decision on behalf of the users.

In languages such as C or C++ the user can decide where data is allocated and for some special cases it may be significantly faster to allocate from the stack compared to allocating from the heap.

This has to do with how heap allocations are handled for C / C++. In fact heap allocation is pretty fast in .NET (except when it triggers a garbage collect), so even if you could decide where to allocate, my guess is that the difference would not be significant.

However, since the heap is garbage collected and the stack is not, obviously you would see some differences in certain cases, but it is hardly relevant given the fact that you don't really have a choice in .NET.

Solution 4

I think the simplest reason is that if it is in the Heap the the garbage collection needs to deal with the variable once it is no longer needed. When on a Stack, the variable is dismissed with whatever was using it, such as a method that instantiated it.

Solution 5

In my opinion knowing about the differences between the stack and heap and how things are allocated on it can be very helpful when you really start thinking about performance of your application. The following questions make it essential to understand the differences: What do you think is faster and more efficient for .NET to access? - Stack or Heap. In what scenarios .NET may place a value type of the heap?

Share:
130
hyunwookcho
Author by

hyunwookcho

Updated on June 05, 2022

Comments

  • hyunwookcho
    hyunwookcho almost 2 years

    My handler will record the camera screen every 5 minutes

    recently, I found handler runs in duplicate.

    handler is before record the camera screen, create record file name.

    if normal, 15:00:00.mp4 , 15:05:00.mp4, 15:10:00.mp4.

    but current my state is 15:00:00.mp4, 15:02:15.mp4, 15:05:00.mp4, 15:07:15.mp4.

    It seems that the same handler is duplicated and the 2 are executed.

    so, I want if there is a handler already working, delete the old handler, execute new handler.

    then, I think solve same handler duplicate problem. is right?

    to sum it up, 1. Before doing handler.sendEmptyMessage, Is it possible to check if the same handler is working?.

    1. if 1 is possible, How to delete a running handler and run only the new handler.

    current my source.

    private RecHandler mHandler = new RecHandler(this);
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    ...
        mHandler.sendEmptyMessage(REQUEST_HANDLE_INIT_RECORD);
    }
    

    RecHandler.class

    public class RecHandler extends Handler {
    
       private final SoftReference<MainActivity> weak;
        public RecHandler(MainActivity act) {
           weak = new SoftReference<BlackEyeActivity>(act);
        }
           @Override
           public void handleMessage(Message msg) {
               MainActivity act = weak.get();
               RecHandler mHandler = new RecHandler(act);
    
               if (act != null) {
                   switch (msg.what) {
                        case REQUEST_HANDLE_INIT_RECORD:
                            initCapturing(); //init camera preview..
    
                            mHandler = new RecHandler(act);
                            mHandler.sendEmptyMessageDelayed(REQUEST_HANDLE_START_RECORD, 1000); //after 1 second, start REQUEST_HANDLE_START_RECORD.
                            this.removeMessages(REQUEST_HANDLE_HOLD_RECORD);
                            break;
    
                        case REQUEST_HANDLE_START_RECORD :
                             startRecording(); //start Recording.. record file 5 minute.
                             mHandler.sendEmptyMessageDelayed(REQUEST_HANDLE_HOLD_RECORD, 300000); //after 5 minute, start REQUEST_HANDLE_HOLD_RECORD.
                             this.removeMessages(REQUEST_HANDLE_INIT_RECORD);
                             break;
    
                        case REQUEST_HANDLE_HOLD_RECORD:
                             stopRecording();
    
                             mHandler.sendEmptyMessageDelayed(REQUEST_HANDLE_INIT_RECORD, 1000); //after 1 second, start REQUEST_HANDLE_INIT_RECORD.
                             this.removeMessages(REQUEST_HANDLE_START_RECORD);
                             break;
    

    so, My handler if always record, repeat INIT(1 seconds) -> START (5 minute) -> HOLD(1 seconds)

    if you know how to check if the same handler is working, and how to delete a running handler and run only the new handler. please advice for me.

  • Jon Skeet
    Jon Skeet over 15 years
    While your example and explanation are correct, you've demonstrated a counterexample to your first sentence. What is "Foo.X"? An int, which is a value type - and yet it always lives on the heap. The claim of "classes are heap allocated, structs are stack allocated" is an oversimplification.
  • josesuero
    josesuero over 15 years
    A better wording would be to say that value types are allocated where they're declared. If they're declared as local variables in a function, they're on the stack. If they're declared as members in a class, they're on the heap, as part of that class.
  • Jader Dias
    Jader Dias over 15 years
    I will not vote up this answer because it mixes reference vs value implications with heap vs stack implications.
  • Wim Coenen
    Wim Coenen over 15 years
    Thanks for the correction, it has triggered an "Aha!" moment. I now realize that stack-vs-heap is a relatively unimportant implementation detail in C#, and that value-vs-reference is the real issue here. I should have explained it that way.
  • MordechayS
    MordechayS over 15 years
    Someone might correct me on this, but aren't class members/properties also stored on the heap? e.g. person.Age = 30; is on the heap
  • Wim Coenen
    Wim Coenen over 15 years
    @chris: Yes, that's what Jon is saying in the first comment, and why I added a note "look at the comments". What's the best practice here, should I go in and fix the post proper instead of referring to the comments?
  • Wim Coenen
    Wim Coenen over 15 years
    I went ahead and fixed it proper since people appear to skip over the "look at the comments" note.
  • Veverke
    Veverke almost 8 years
    Thanks for this fundamental remark: In .NET there's little to discuss as it is not the user of a type who decides where to allocate instances, while In languages such as C or C++, the user can decide where data is allocated and for some special cases it may be significantly faster to allocate from the stack compared to allocating from the heap.
  • Elham Azadfar
    Elham Azadfar almost 6 years
    This makes perfect sense, and I really appreciate you taking the time to provide such a detailed response!
  • Dave Black
    Dave Black about 5 years
    Part of this answer is incomplete. The answer says "...the default maximum stack size on Windows is 1MB". This is true only for 32-bit processes. A 64-bit Windows process has a default stack size of 4MB.
  • JamesHoux
    JamesHoux over 4 years
    The link is broken. Does anyone know where the article could still be read?
  • JamesHoux
    JamesHoux over 4 years
    Here is an excellent article on the use of Array Pools (as suggested in the answer): adamsitnik.com/Array-Pool
  • JamesHoux
    JamesHoux over 4 years
    For clarification to other readers of this answer: the performance differences shown are not due to "the stack vs heap" per se. The cost of larger objects is due to the garbage collector promoting gen0 to gen1 and gen2 objects. In the case of small objects, the objects are probably all remaining as gen0, which is making their performance comparable to the stack. Author Tomas Kubes probably recognizes this... as he suggests using array pooling, which completely bypasses GC costs and makes heap performance same as stack.
  • JamesHoux
    JamesHoux over 4 years
    Also, for anyone interested in Array Pooling when dealing with very large object heaps, have a look at Piles. Piles are a way to represent objects in a single gigantic array, making them completely invisible to the garbage collector and giving incredible performance.
  • Jon Skeet
    Jon Skeet over 4 years
    @JamesHoux: I'm afraid I don't think I've got that to hand any more. Will remove that paragraph. But it's likely to be very similar to blogs.msdn.microsoft.com/ericlippert/2009/04/27/…