C# & CLR Internals (50 Qs)•Part 1: Core Language, CLR & Memory Architecture (1 - 10)
What is Boxing and Unboxing, and how do you avoid its performance penalty?
senior LevelFormsPerformanceSystem Design
In Simple Words:
- Boxing: Converting a Value Type to a Reference Type (or interface), allocating an object on the managed heap and copying the value into it.
- Unboxing: Extracting the value type back out from the heap object to the stack.
- Penalty: Heavy GC pressure and CPU overhead in tight loops.
- Avoidance: Use Generics (
List<int>instead of legacyArrayList),inparameters, and generic interfaces (IEquatable<T>).