Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@taiga_takahari

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

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

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;

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

10
Help us understand the problem. What is going on with this article?
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
10
Help us understand the problem. What is going on with this article?