C#: boxing and unboxing

We should know boxing and unboxing clearly. But what's the actual performance affect happened in that process? Below diagram can give a overview:

A boxing process will bring in two copies of the same data on both stack and managed heap finally; while the latter unboxing will bring in three copies of the same data: two on the stack and one on the managed heap. This can easily happen in following exampled case:

ArrayList prices = new ArrayList();
decimal amount1 = 7.50m;
decimal amount2 = 1.95m;
prices.Add(amount1);
prices.Add(amount2);
foreach (decimal amount in prices)
{
Console.WriteLine(“Amount: {0}”, amount);
}

原文地址:https://www.cnblogs.com/taoxu0903/p/1670943.html