如何讓Foreach循環運行的更快

來源:互聯網
上載者:User
foreach是一個對集合中的元素進行簡單的枚舉及處理的現成語句﹐用法如下﹕ 1using System;
 2using System.Collections;
 3namespace LoopTest
 4{
 5class Class1
 6{
 7static void Main(string[] args)
 8{
 9// create an ArrayList of strings
10ArrayList array = new ArrayList();
11array.Add("Marty");
12array.Add("Bill");
13array.Add("George");
14// print the value of every item
15foreach (string item in array)
16{
17Console.WriteLine(item);
18}
19}
20}
21

你可以將foreach語句用在每個實現了Ienumerable介面的集合裡﹐如果要瞭解更多的foreach的用法﹐可查相關SDK.
在編譯的時候﹐C#編輯器會對每一個foreach區域進行轉換.

 1IEnumerator enumerator = array.GetEnumerator();
 2try 
 3{
 4string item;
 5while (enumerator.MoveNext()) 
 6{
 7item = (string) enumerator.Current;
 8Console.WriteLine(item);
 9}
10}
11finally 
12{
13IDisposable d = enumerator as IDisposable;
14if (d != null) d.Dispose();
15}
16

這說明在後台﹐foreach的管理會給你的程式帶來一些增加系統開銷的額外代碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.