Which is the best way to loop thru an list? is for loop better than numerous List class’s find method? Also if i use its find methed as i mentioned below which is anonymous delegate an instance of an predicate delegate, does it better than using lambda expression? Which one will execute faster?
var result = Books.FindLast(
delegate(Book bk)
{
DateTime year2001 = new DateTime(2001,01,01);
return bk.Publish_date < year2001;
});
It’s a complex question because it involves a lot of different topics.
In general, delegates are many times slower than a simple function call but to enumerate a list (via foreach) is terribly slow too.
If you really care about performance (but do not do it a-priori, profile!) you should avoid delegates and enumerations. First big step (whenever possible) could be to use a Hashtable instead of a simple list.
Examples
Now some examples, I’ll write the same function in different ways, from the more readable (but slower) to the less readable (but faster). I omit every error checking but a real world function shouldn’t (at least some asserts are required).
This function uses LINQ, it’s the more easy to understand but the slowest.
Note the
bookscan be a generic enumeration (it’s not required to be aList<T>)Same as before but without LINQ. Note that this function
handles a special case: the list doesn’t contains any eligible book.
Same as before but without enumeration, note that this function
handles a special case: the list doesn’t contains any eligible book.
Same as before but with a
SortedList<T>as suggested by @MaratKhasanov. Please note that with this container you’ll have the good performances during the search but insertion of a new element can be more slow than a normal unsorted list (because list itself must be kept sorted). If the number of elements in the list is very high you may think to write your own sorted list using aHashtable(using, for example, the year as key for the first level).Now an example a little bit more complex but with best search performance. Algorithm is derived from an ordinary binary search (note that if you want to match the first element that matches the predicate you may use the List.BinarySearch method directly).
Note that code is untested and can be optimized too, please consider it just an example.
Before moving to a more complex container you may think to keep your
SortedList<T>unsorted until the first search. It’ll be really slow (because it will sort the list too) but inserts will be as fast as a normal list (but you have to try with real world data). Anyway last algorithm can be optimized a lot.Maybe if you have so many items in your collection that you can’t manage them with a normal collection you may think to move everything to a database…lol