//计算for循环一定次数所用的时间 Stopwatch sw = new Stopwatch(); for (int i = 0; i < 10000000000; i++) { } sw.Stop(); Console.WriteLine(sw.Elapsed); Console.ReadKey();
两者区别
在循环次数不高的时候,for和foreach两者的效率基本一致。
在循环次数十分巨大的时候,foreach的效率要比for高很多倍。
在写法上,foreach的写法要稍微简单一些。
List泛型集合
创建泛型集合对象
//创建泛型集合对象 List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3);
int n = 10; object o = n;//装箱 int nn = (int)o;//拆箱
ArrayList和List泛型集合的区别
为什么使用List泛型集合而不使用ArrayList?
ArrayList操作的是Object类型,可能会发生装箱操作。
装箱就会不停地做类型转换,影响性能,应该避免装箱和拆箱。
ArrayList list = new ArrayList(); //List<int> list = new List<int>(); Stopwatch sw = new Stopwatch(); sw.Start(); //这个循环发生了100万次装箱操作 for (int i = 0; i < 10000000; i++) { list.Add(i); } sw.Stop(); Console.WriteLine(sw.Elapsed);//List泛型集合比ArrayList操作快10倍左右 Console.ReadKey();
装箱和拆箱的条件
判断两种类型是否发生了装箱或者拆箱:
如果两种类型是继承关系,则有可能发生装箱或者拆箱。
如果两种类型没有任何继承关系,则没有发生任何装箱或者拆箱。
//这个地方没有发生任何的装箱 string str = "123"; int n = Convert.ToInt32(str);//int和string类型没有任何继承关系
//发生了装箱 int a = 10; IComparable i = a;//int继承自IComparable接口