Created
April 10, 2013 03:32
-
-
Save hatelove/5351570 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
這兩天跟一些前輩在討論,如果只是要判斷集合有沒有資料,到底是要用Count() > 0 比較好,還是用 Any() 比較好。 | |
而在一些資料結構上,如List<T>,Count() 跟Count的差異到底在哪。 | |
這邊給個Count()擴充方法的程式碼: | |
https://gist.github.com/regionbbs/17c2d551479171c48eb8 | |
大家應該都知道,IEnumerable其實就是給foreach用的串列集合而已,除了給foreach用的以外,上面並沒有甚麼其他多餘的屬性或方法。 | |
而Count這個屬性在一堆集合裡面可以用,是因為這堆集合都有實作了ICollection or ICollection<T>,因此有Count可以用。 | |
歸納一下結論: | |
1. 如果你的集合仍是IEnumerable<T>,還不是ICollection<T>等資料結構的型別,要判斷是否有無資料存在,請用Any(),不要用Count() > 0,效率會好一些。 | |
2. 如果你的集合,已經是ICollection<T>的類別,要判斷是否有資料存在,請用Count屬性 > 0,不要用Any() 或是 Count() >0,效率會好一些。 | |
3. 有一些前輩則是認為,一致性要比Count()裡面需要多花兩次轉型跟判斷式的effort重要一些,所以他們不管是IEnumerable<T>或是ICollection<T>,一律都使用Count() ,而不會使用Count屬性。 | |
最後,我自己偏向寫法是1+2。因為可以很清楚的表達意思,不會造成維護上的困擾,也可以達到最好的performance。 | |
Stackoverflow上也有一篇討論串在講這件事,大家可以參考一下: | |
http://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0 | |
上面的一個重點是,如果集合已經有Count屬性可以用,那麼Count會比Any() 還快。因為Any() 還需要GetEnumerator()/MoveNext()/Dispose() ,雖然執行只有一次,但也是要花費點資源的。 | |
PS: 剛剛看到小朱的文已經整理好了,這邊也跟著貼上來:http://www.dotblogs.com.tw/regionbbs/archive/2013/04/10/when.to.use.any.or.count.in.linq.aspx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment