0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

少しでも効率よく

Posted at

はじめに

要素有無を判定するときに、Countメソッドを使ってリストを要素数を数えて、0以上とか判定するより、Anyメソッドを使って要素有無判定する方が処理効率は良い
コードレビューで上記のコメントをいただいたため、内容を調べてみた

コードサンプル

Countメソッドを使う場合

var list = Enumerable.Range(1,10000).ToList();
var hasElements = list.Count() > 0;

Anyメソッドを使う場合

var list = Enumerable.Range(1,10000).ToList();
var hasElements = list.Any();

Countメソッドを使った場合、すべての要素を数えるため、時間がかかる
Anyメソッドを使った場合、最初の要素を見つけた時点で処理を終了するため、早くなる

比較

以下記事で細かく書かれている
ベンチマークの結果としても、Anyメソッドの方がパフォーマンスが良い
https://dexall.co.jp/articles/?p=1527

結論

実際の現場では微々たる差異かもしれませんが、要素のあるなし判定をするときは、Countメソッドを使って要素有無を判定するより、Anyメソッドを使った方が効率的になる
コードを見ても、Anyの方が、直感的で分かりやすいため、要素数をカウントするのではなく、存在有無で判定していくと可読性も良くなる

(おまk)
.NETのバージョンよれば警告として出てきそう
https://learn.microsoft.com/ja-jp/dotnet/fundamentals/code-analysis/quality-rules/ca1827

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?