- EkardNT
- Mar 31, 2011
-
|
One issue I see is that even when one predicate approves an item, all other predicates are still run on that item. This is also why you need the HashSet, because if all n predicates approve an item it will be added n times. I suggest reversing the order of your two foreach loops so that the totalItems list is only examined once, and breaking out of the inner predicate loop once a match is found.
code:public IEnumerable<Item> GetItems()
{
List<Item> totalItems = GlobalAccessor.GetTotalItems(); // 2500 thingamabobs
List<Item> selectedItems = new List<Item>();
foreach(Item item in totalItems)
{
foreach(Predicate<Item> pred in itemSpecifiers)
{
if(pred(item))
{
selectedItems.Add(item);
break;
}
}
}
return selectedItems;
}
Here's the same thing using Linq.
code:public IEnumerable<Item> GetItems()
{
var totalItems = GlobalAccessor.GetTotalItems();
return totalItems.Where(item => itemSpecifiers.Any(pred => pred(item)));
}
It's still O(totalItems.Count * itemSpecifiers.Count), which will occur when none of the predicates accept any item, but at least now you spend as little time per item as possible instead of the maximum time every time.
|
#
¿
Jun 26, 2014 17:55
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 2, 2024 20:17
|
|