Help us understand the problem. What is going on with this article?

AnyでFirst取得するかFirsrOrDefaultで取得するか

More than 5 years have passed since last update.

気になったのでちょっと検証してみた。

if (list.Any())
 return list.First();

var data = list.FirstOrDefault();
if (data != null)
 return data;

で、どっちが速いのか。

Stopwatchで前後でStart、Stopで計ったところ、

回数 AnyとFirst FirstOrDefault
1回目 0.0002417 0.0001677
2回目 0.0002348 0.0001782
3回目 0.0002376 0.0001665

ってことで後者の方が速いらしい。

なので今後は後者を使おう。

[追記]

よくよく考えてみたら、

if (list.Any(x => x.hoge == 1))
 return list.First(x => x.hoge == 1);

より

var data = list.FirstOrDefault(x => x.hoge == 1);
if (data != null)
 return data;

の方が速いのは明確だったか…。

duo
総合 ITベンチャーです。バーチャルライブ配信アプリ「IRIAM」、「ミライアカリ」をはじめとするバーチャルタレント事業、アミューズメント事業を展開しています。
https://zizai.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした