Published Oct 3, 2013

Boxing and Unboxing in .NET

    Explore the intricate world of .NET's boxing and unboxing operations, uncovering how to optimize performance using generic collections while examining the necessity and implications of these techniques on legacy code, memory, and CPU efficiency.
    Episode Highlights
    Coding Blocks logo

    Popular Clips

    Episode Highlights

    • Memory Impact

      Boxing in .NET significantly impacts memory usage by moving values from the stack to the heap. Joe Zack explains that a 32-bit integer on the stack takes up 32 bits, but when boxed, it requires additional memory for a pointer and sync block index, increasing its size to 92 or 128 bits 1. This increase in size is due to the need for a pointer to the heap, where the boxed value resides, and the sync block index used for locking 2.

      A 32-bit integer plus the 32-bit pointer, or, you know, could be 64 and 64 bits. And that 32-bit sync block index ends up being 92 bytes or sorry bits or 128.

      --- Joe Zack

      This memory overhead is a significant consideration when dealing with boxed values in .NET applications.

         

      Performance Costs

      The performance costs of boxing and unboxing in .NET are notable, involving additional reads and CPU usage. Joe Zack highlights that boxed values require an extra read, as accessing them involves fetching a pointer and looking up the object on the heap 1. This process is slower compared to accessing values directly on the stack. Additionally, Michael Outlaw points out that implicit boxing, such as in string formatting, can occur without developers realizing it, adding unnecessary overhead 3.

      Boxing and unboxing is big, slow, ugly, sneaky and largely unnecessary.

      --- Joe Zack

      These performance hits underscore the importance of understanding when boxing occurs to optimize .NET applications.

         

      Heap Management

      Boxing affects heap management by clogging it with short-lived values, which can lead to inefficiencies. Joe Zack notes that these values, when frequently created, occupy generation zero on the heap, potentially filling it up quickly 1. Although garbage collection can clean up these values, the process adds overhead to the system. Michael Outlaw humorously refers to the negative reputation of boxing and unboxing in the programming community, likening it to "seven deadly sins" 4.

      Your short-lived values actually clog the heap.

      --- Joe Zack

      Efficient heap management requires minimizing unnecessary boxing to maintain optimal performance.

    Related Episodes