Foreach使用

在.net环境里,如果需要遍历集合的话,常用的就是foreach,根据Effective C#所说,也是最佳的实践方式。
下面首先比较各种遍历集合的方式:
 1int [] foo = new int[100];
 2
 3// Loop 1:
 4foreach ( int i in foo)
 5  Console.WriteLine( i.ToString( ));
 6
 7// Loop 2:
 8for ( int index = 0;
 9  index < foo.Length;
10  index++ )
11  Console.WriteLine( foo[index].ToString( ));
12
13// Loop 3:
14int len = foo.Length;
15for ( int index = 0;
16  index < len;
17  index++ )
18  Console.WriteLine( foo[index].ToString( ));
第一种是foreach,第二种是传统的for,第三种看似对第二种做了“优化”。
有过C++经验的人都会觉得第三种的优化很正常,但是C#的编译器可不这么想。由于C#强调安全编程,对象的访问都会检查是否越界。不管我们是不是自己保证不越界,编译器都会帮我们进行越界检查。因此,第三种实际上会产生两次下标检查。
 1// Loop 3, as generated by compiler:
 2int len = foo.Length;
 3for ( int index = 0;
 4  index < len;
 5  index++ )
 6{
 7  if ( index < foo.Length )
 8    Console.WriteLine( foo[index].ToString( ));
 9  else
10    throw new IndexOutOfRangeException( );
11}
是的,编译器确实做了两次下标检查,呵呵,帮倒忙了。

转载于:https://www.cnblogs.com/capsun/archive/2008/06/27/1231186.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值