以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 编程心得 』   (http://bbs.xml.org.cn/list.asp?boardid=42)
----  for循环C#与C/C++的性能区别。  (http://bbs.xml.org.cn/dispbbs.asp?boardid=42&rootid=&id=47130)


--  作者:DavidPotter
--  发布时间:5/19/2007 10:02:00 AM

--  for循环C#与C/C++的性能区别。
以C#为例的3种循环:
int [] foo = new int[100];
Loop1:
foreach(int i in foo)
 Console.WriteLine(i.ToString());

Loop2:
for(int i=0; i<foo.Length; i++)
 Console.WriteLine(foo[i].ToString());

Loop3:
int len=foo.Length;
for(int i=0; i<len; i++)
 Console.WriteLine(foo[i].ToString());
In C/C++, we know that compared to Loop3, Loop2 does not need compute the length of foo again and again.
However,
different with C/C++
the performance of Loop3 is worse than Loop2.
C#code runs in a safe, managed enviroment. Every memory location is checked, including indexes.
For Loop3:
generated by complier:
int len=foo.length;
for(int i=0; i<len; i++)
{
 if(i<foo.Length)
  Console.WriteLine(foo[i].ToString());
 else
  throw new IndexOutOfRangeException();
}

ref: [Bill Wagner] Effective C#-50 Specific ways to improve Your C#.


--  作者:netjian
--  发布时间:2/17/2008 11:39:00 AM

--  
Get it ,the one more "if" may reduce the C# efficiency.
I remember .  be in case of using it any more.
W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
31.250ms