Search code examples
c#performanceobjectstructcreation

Does object creation overhead apply to structs?


I'm asking for a project in C#, but I assume this question applies to other languages as well. I've heard that massive object creation and destruction causes massive overhead and performance issues. I'm wondering if I can get around this by simply using structs instead of objects.


Solution

  • Here is some facts that you must now about struct and class in C# :

    • A struct in C# is faster to create than a class since it's allocated on the stack and not on the heap
    • struct is a value type, class is a reference type. So working with a reference type (passing it as parameter, copying it, ...) is much faster than working with the value type. see Difference between struct and class
    • struct fields are fast to access than class fields since they are allocated on the stack

    Here is some facts about how the GC works in .Net :

    • You can't have control on when the GC is triggered by the CLR, it can interrupts your program at any time (there is some options that you can use to tell the CLR that you are running a sensitive part of the code but it doesn't prevent the GC from running if memory is needed. see GC Latency Modes)
    • You can't have control on the time that the GC takes to do it's work
    • When the GC is doing a full collection, it freezes all your program threads (depending on whether you are in gcConcurrent or gcServer mode see gcServer mode ).

    Knowing all of that and to be short, if you don't want your program to suffer from the GC work, you have to use reference types for objects that will live the longer in your program, and use value types for objects that will be used for a very short time and in a very localized scope.