using System;
using System.Diagnostics;
namespace TestTypeChange
{
public class MyClass{
public int id = 0;
public string name = "";
public MyClass(int _id,string _name){
id = _id;
name = _name;
}
}
class MainClass
{
public static void Main (string[] args)
{
Stopwatch stopwatch;
object obj_ptr = null;
MyClass myclass = new MyClass (0, "cjane");
MyClass ref_myclass = null;
int count = 100000000;
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
ref_myclass = myclass;
stopwatch.Stop();
Console.WriteLine("class to class: " + stopwatch.Elapsed);
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
obj_ptr = myclass;
stopwatch.Stop();
Console.WriteLine("class to object: " + stopwatch.Elapsed);
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
ref_myclass = (MyClass)obj_ptr;
stopwatch.Stop();
Console.WriteLine("object to class: " + stopwatch.Elapsed);
int val = 100;
int cp_val = 0;
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
ref_myclass = myclass;
stopwatch.Stop();
Console.WriteLine("value to value: " + stopwatch.Elapsed);
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
obj_ptr = val;
stopwatch.Stop();
Console.WriteLine("value to object: " + stopwatch.Elapsed);
stopwatch = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
cp_val = (int)obj_ptr;
stopwatch.Stop();
Console.WriteLine("object to value: " + stopwatch.Elapsed);
}
}
}
測試結果:
class to class: 00:00:00.3463484
class to object: 00:00:00.3520921
object to class: 00:00:00.3760758
value to value: 00:00:00.3303531
value to object: 00:00:01.9317834
object to value: 00:00:00.3482110
測試得出C# 引用類型間的轉換幾乎和賦值時候差不多,性能損耗幾乎忽略不計
但如果是整型值類型間的轉換,把整型值類型轉為object的時候,性能比較低
有興趣的可以試試下字符串與object間的轉換
