C# Boxing vs Unboxing: Performance Cost Explained

Boxing is the automatic wrap of a value type (int, bool, struct) into an object on the managed heap. Unboxing is the reverse cast that pulls the value back out. Both allocate memory and create a tiny object—CPU and GC pay the tab.

Developers often sprinkle object parameters or non-generic collections (ArrayList) without noticing. One quick cast later, they’ve added silent heap churn. It feels “safe” until profiler graphs spike because hidden allocations compound under load.

Key Differences

Boxing copies the value into a fresh heap object; unboxing copies it back to the stack. Boxing happens implicitly when you assign a value type to object, interface, or dynamic. Unboxing is always explicit with a cast and throws if the type doesn’t match.

Which One Should You Choose?

Avoid both. Prefer generics, Span, or ref locals to keep data on the stack. When interop or older APIs demand object, box once and reuse the reference. Measure with BenchmarkDotNet—microseconds add up in tight loops.

Examples and Daily Life

Logging an int to an ILogger that takes object? Boxing. Storing Points in an ArrayList? Double boxing on every add and cast. Switch to List and save the GC from a cleanup party.

Does boxing allocate every time?

Yes, each boxing call creates a new heap object unless the runtime caches primitives like small integers.

Can structs ever escape boxing?

If they implement interfaces and are accessed through that interface, boxing still occurs. Use generic constraints to stay allocation-free.

How do I spot boxing in Visual Studio?

Enable the “Boxing” diagnostic under Debug > Performance Profiler or inspect IL for box/unbox opcodes.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *