简体   繁体   中英

Which is better in performance

Which of the below is better in performance using LINQ?

sets.FirstOrDefault(x=>x.name=="xxx")

or

sets.FirstOrDefault(x=>!string.IsNullOrEmpty(x.name) && x.name.Equals("xxx",StringComparison.InvariantCultureIgnoreCase));

Here name can be null . I'm using this kind of query 20+ times in my app.

Is there any better approach?

There is a major difference between the two statements, so you just can't only judge them on performance.

The first one performs better, but the second one will give different results (since it doesn't check on upper/lower case and diacritics).

Optionally, you could rewrite the second like this:

sets.FirstOrDefault(x => string.Equals(x.name, "xxx",StringComparison.OrdinalIgnoreCase));

It doesn't need the string.IsNullOrEmpty which will make the second call a little faster than it was.

As noted by weston : The use of OrdinalIgnoreCase performs better then InvariantCultureIgnoreCase , hence this notice of Microsoft.

如果您只运行20次左右,那就没关系了,但是第一个选项会更快,因为第二个选项会执行额外的null检查。

I have not tested it, but I'd bet sets.FirstOrDefault(x=>x.name=="xxx") is faster. Simple reason - it does less work, and less work is faster.

Although, this type of performance improvements are usually not worth it. You'll gain much more performance benefits by looking at the architecture of your app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM