Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Predicate of a class to Search Generic list - Faster than looping?

Lets say we have a generic list of Class1, typically having ~100 objects for a given session. I would like to see if the list has a particular object. ASP.NET 2.0 allows me to do this:

Dim objResult as Class1 = objList.Find(objSearch)

How does this approach rate when compared to a traditional For loop, looking at a performance perspective?

How would this vary with increase or decrease in length of the list?

like image 455
Srikanth Venugopalan Avatar asked Dec 29 '22 18:12

Srikanth Venugopalan


1 Answers

It's exactly the same as looping - that's what it does internally.

If your list is sorted and you're looking for a particular value, you could potentially use BinarySearch instead - but if you think about it, if you don't know anything about the predicate or the order of the data, it has to look through each item until it finds a match. As it happens, Find is specified to return the first item in the list... so it just looks through in the obvious order.

This will be linear with the size of the list - i.e. on average, searching a list which is 10 times as big will take 10 times as long. Of course, it depends on whether and where a match is found; if the first item matches in every case, it'll finish in the same time no matter how big the list is :)

To be honest, with only 100 objects it sounds like it's very unlikely to be a bottleneck.

like image 63
Jon Skeet Avatar answered Feb 13 '23 20:02

Jon Skeet