Boxing
A value type lives where it is declared: a local on the stack, a field inside its object, an element inside its array. An object variable holds a reference to the heap, so assigning an int to one makes the runtime allocate a small object that contains the int. That allocation is boxing, and the reverse is unboxing.
What boxing does
GC.GetAllocatedBytesForCurrentThread reports the bytes this thread has allocated so far, so the difference around one assignment is the cost of that assignment. The program measures one box, then a hundred thousand:
var before = GC.GetAllocatedBytesForCurrentThread();
object boxed = 42;
var after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"one box {after - before}");
before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 100000; i++)
{
object value = i;
if ((int)value != i)
{
Console.WriteLine("no");
}
}
after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"loop {after - before}");
var ints = new List<int>();
var objects = new List<object>();
before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++)
{
ints.Add(i);
}
after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"list int {after - before}");
before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < 1000; i++)
{
objects.Add(i);
}
after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine($"list object {after - before}");
dotnet run
one box 24
loop 2400000
list int 8392
list object 40568
One box is 24 bytes: eight for the object header, eight for the method table pointer and eight for the int, padded to the alignment of the heap. A hundred thousand of them are 2 400 000 bytes, and the unboxing comparison confirms the value came back. The two lists then separate: a list of a thousand ints grows its array and allocates 8 392 bytes, while the list of objects allocates 40 568.
The measured cost
| Operation | Bytes allocated |
|---|---|
| one boxed int | 24 |
| 100 000 boxed ints | 2 400 000 |
| List<int> with 1000 items | 8 392 |
| List<object> with 1000 boxed ints | 40 568 |
The list of objects pays twice: the boxes are 24 000 bytes, and its internal array holds references instead of four-byte integers, which makes it larger and forces a copy on each growth. The 8 392 of the int list is the capacities 4, 8, 16 and so on, rounded by the allocator, not a thousand separate allocations.
A list of int and a list of object
The generic list of a value type stores the values inline and needs no box; the list of object stores a reference per element and boxes every value that goes in. The same difference appears in a method that takes object, in an ArrayList, and in an interface-typed variable that holds a struct: the compiler must box the struct to satisfy the reference. A generic method with a value type avoids all of it.
How to avoid it
- Keep the value typed: List<int> instead of ArrayList, T instead of object.
- A method that only reads a value takes the value type or a generic constraint, not object.
- A struct that implements an interface is boxed when it is used through that interface; a generic method constrained to the interface avoids the box.
- A dictionary of an enum key boxes nothing if the key is the enum type; an enum key typed as object boxes on every lookup.
A box is not a bug by itself: a call to object.ToString, a collection of mixed types and a logging call that takes object all box on purpose. The cost matters when the code is a loop that runs a million times, which the next lesson measures with a span instead.
Exercises
- Measure object value = 42L and compare the box with the int one.
- Add a million items to a List<object> and watch the collection counts.
- Box a struct with two ints and measure it; explain the number.
- Write a generic method and an object method that return the same value, and measure both in a loop.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is boxing?
Answer
Copying a value type into a heap object so a reference can point at it
The runtime allocates the box, which the measured 24 bytes show.
-
How many bytes did one boxed int cost in the measurement?
Answer
24
The program printed one box 24.
-
What does this program print?
object value = 5; Console.WriteLine(value.GetType().Name);Answer
Int32
The boxed object knows the type of the value it holds.
-
What does this program print?
var ints = new List<int>(); ints.Add(1); Console.WriteLine(ints.Count);Answer
1
One item was added to the list.
-
What does unboxing require?
Answer
The exact type that was boxed
A boxed int can only be unboxed to int, not to long or double.
-
Why does List<object> allocate more than List<int>?
Answer
Each int is boxed and the array holds references
The measured 40 568 bytes against 8 392 are the boxes and the references.
-
What does this program print?
object a = 1000; object b = 1000; Console.WriteLine(ReferenceEquals(a, b));Answer
False
Two boxes are two objects, even when they hold the same number.
-
What does GC.GetAllocatedBytesForCurrentThread report?
Answer
The bytes allocated on this thread so far
The program took the difference around each measurement.
-
Which type stores ints without boxing?
Answer
List<int>
A generic list of a value type stores the values inline.
-
When is a box acceptable?
Answer
A single call that takes object, outside a hot loop
The cost is real but small; it matters when it is multiplied by a loop.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev