装箱和拆箱:
把值类型转换为引用类型 -> 装箱
把引用类型转换为值类型 -> 拆箱
static void Main(string[] args)
{
int num = 1;
object obj = num; // 装箱操作 - 把值类型转换为引用类型
int n = (int)obj; // 拆箱操作
}
装箱和拆箱操作对性能影响非常大,应减少此类操作:
下边是1千万次循环,每次循环向ArrayList中添加一个int类型元素,在添加时,发生装箱操作(每次都需要把值类型转换为object类型):
static void Main(string[] args)
{
ArrayList li = new ArrayList();
Stopwatch time = new Stopwatch();
time.Start();
for(int i = 0; i < 10000000; i++)
{
li.Add(i); // Add参数类型为一个object,但是传的是int类型,会发生装箱操作
}
time.Stop(); // 停止某个时间运行
Console.WriteLine(time.Elapsed); // 00:00:12.0376827获取总运行时间
Console.Read();
}
下边同样一亿次循环,我们使用泛型类看下,差距不是一点半点的:
static void Main(string[] args)
{
List<int> n = new List<int>();
Stopwatch time = new Stopwatch();
time.Start();
for(int i = 0; i < 10000000; i++)
{
n.Add(i); // Add不会发生装箱操作,因为Add参数也是int类型
}
time.Stop(); // 停止某个时间运行
Console.WriteLine(time.Elapsed); // 00:00:00.9277815获取总运行时间
Console.Read();
}
注意点:
查看两个类型是否发生了装箱和拆箱,首先看他们之间是否存在继承关系,如果无继承关系,那么绝对不会发生装箱和拆箱操作。
下边字符串为引用类型,把字符串转int类型,不会发生拆箱,因为二者没有继承关系!!!
string str = "123";
int n = Convert.ToInt32(str);