核心概念
- 值型別 (int, struct, enum...) 儲存在堆疊,直接包含資料。
- 參考型別 (class, interface, object, string...) 儲存在堆積,變數持有參考。
- 裝箱:值型別 → 參考型別 (隱式轉換為
object 或介面)。配置堆積記憶體、複製值、產生參考。
- 拆箱:參考型別 → 值型別 (顯式轉型)。檢查型別、複製值回堆疊。
圖解流程
值型別變數 (Stack) 裝箱 物件參考 (Stack) → 物件實例 (Heap)
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ int val = 42 │ ──────► │ new Box(42) │ ───► │ ref → [42] │
└──────────────┘ 配置/複製 └──────────────┘ └──────────────┘
拆箱:ref → 型別檢查 → 複製回 Stack (int unboxed = (int)ref;)
程式碼示範
using System;
using System.Diagnostics;
class BoxingDemo
{
static void Main()
{
int val = 42;
// 裝箱
object boxed = val; // 隱式裝箱
// 等同: object boxed = (object)val;
// 拆箱
int unboxed = (int)boxed; // 顯式拆箱,型別必須完全一致
// 介面裝箱
IComparable cmp = val; // 實作介面也會裝箱
// 效能測試
const int N = 10_000_000;
long sum = 0;
// 直接運算 (基準)
var sw = Stopwatch.StartNew();
for (int i = 0; i < N; i++) sum += i;
sw.Stop();
Console.WriteLine($"直接運算: {sw.ElapsedMilliseconds} ms");
// 裝箱/拆箱
sum = 0;
sw.Restart();
for (int i = 0; i < N; i++)
{
object o = i; // 裝箱
sum += (int)o; // 拆箱
}
sw.Stop();
Console.WriteLine($"裝箱/拆箱: {sw.ElapsedMilliseconds} ms (約 {sw.ElapsedMilliseconds / (double)N * 1_000_000:F2} ns/op)");
// 泛型避免裝箱
sum = 0;
sw.Restart();
for (int i = 0; i < N; i++)
{
AddGeneric(i, ref sum);
}
sw.Stop();
Console.WriteLine($"泛型避免裝箱: {sw.ElapsedMilliseconds} ms");
}
static void AddGeneric(int value, ref long sum) => sum += value;
}
效能影響量化
| 操作 | 相對成本 | 記憶體配置 |
| 直接值型別運算 | 1x (基準) | 無 |
| 裝箱 | ~10-20x | Heap 配置 (Gen 0) |
| 拆箱 | ~2-5x | 無新配置,但有型別檢查 |
泛型 List<int> | 1x | 無裝箱 |
非泛型 ArrayList | ~15x | 每次 Add 皆裝箱 |
常見無意裝箱陷阱
避免裝箱的最佳實踐
- 使用泛型集合:
List<T>, Dictionary<TKey,TValue>, Stack<T>, Queue<T>
- 泛型方法/介面:
IEquatable<T>, IComparable<T> 避免介面裝箱。
- 避免非必要的 object 參數:改用多載或泛型。
- 結構體實作介面時:呼叫介面方法會裝箱,考慮提供非介面的強型別方法。
- ValueTuple / record struct (C# 9/10):現代值型別設計減少裝箱需求。
驗證工具
- ILSpy / dotPeek:檢視 IL 是否有
box/unbox.any 指令。
- BenchmarkDotNet:精確量測裝箱對熱路徑的影響。
- Roslyn Analyzer:
CA1819、CA1826 等規則偵測潛在裝箱。