Theme NexT works best with JavaScript enabled

ShunNien's Blog

不積跬步,無以致千里;不積小流,無以成江海。

0%

C# 中 Boxing 與 Unboxing

Boxing (裝箱) 與 Unboxing (拆箱) 會有這兩者的出現,簡單說係因為實值型別參考型別兩者間的處理,不過針對這動作所造成的影響,可以進行簡單的小測試。

  • Boxing
    是一種隱含轉換,是將實值型別轉換為 object 類型(參考型別)或是由這個實值型別實作之任何介面類型的程序。
    Boxing 轉換
  • Unboxing
    將 object 類型明確轉換實值型別,或將介面類型明確轉換為實作介面之實值型別的程序。
    Unboxing 轉換
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
int max = 100000;
int flag = 0;
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
// 經過一次裝箱
for (int i = 0; i < max; i++)
{
string str = " i = " +i;
}
sw.Stop();
Console.WriteLine("one boxing time:" + sw.Elapsed.TotalMilliseconds.ToString());

sw.Reset();
sw.Start();
// 不裝箱
for (int i = 0; i < max; i++)
{
string str = " i = " + i.ToString();
}
sw.Stop();
Console.WriteLine("no boxing time:" + sw.Elapsed.TotalMilliseconds.ToString());

DateTime now = DateTime.Now;

while (!((DateTime.Now.Second - 5) == now.Second))
{
string str = " i = " + flag;
flag++;
}
Console.WriteLine("one boxing 5 second run :" + flag.ToString() + " times");


flag =0;
now = DateTime.Now;
while (!((DateTime.Now.Second - 5) == now.Second))
{
string str = " i = " + flag.ToString();
flag++;
}
Console.WriteLine("no boxing 5 second run :" + flag.ToString() + " times");

輸出結果

1
2
3
4
one boxing time:12.413
no boxing time:9.1419
one boxing 5 second run :26794548 times
no boxing 5 second run :32986447 times

參考資料

歡迎關注我的其它發布渠道