This article is a mirror article of machine translation, please click here to jump to the original article.

View: 3028|Reply: 0

[Source] .NET/C# collection Any() or Count() which is faster

[Copy link]
Posted on 6/28/2023 7:34:31 PM | | | |
Requirements: Recently, my colleagues in the project team changed the data count() > 0 to Any() to judge whether there is data in the collection (not IQueryble query database), and then asked why it was changed (optimized), but there was no answer.

Use benchmarks to compare which of the following Any() and Count() is faster.

Let's start with the conclusion (in .NET Framwork):Count > Any() > Count()In .NET 6, Count() and Any() performance are not much different, but stillAny() is recommended for collecting whether there is data

The test code is as follows:


.NET Framework 4.8.1The benchmark data is as follows:



.NET 6The benchmark data is as follows:



Didn't you say that in .NET Framwork Any() > Count() performance? Why is Count() faster than List? The reason is that the underlying Count() method of List calls the Count field, as shown in the figure below:




(End)





Previous:.NET/C# method parameter NULL null
Next:ASP.NET the difference between ThreadStatic, CallContext, and HttpContext
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com