I want to sort a list of objects using a value that can take some time to compute. For now I have code like this:
public IEnumerable<Foo> SortFoo(IEnumerable<Foo> original)
{
return foos.OrderByDescending(foo => CalculateBar(foo));
}
private int CalculateBar(Foo foo)
{
//some slow process here
}
The problem with the above code is that it will call calculate the value several times for each item, which is not good. The possible optimization is to use cached value (maybe a dictionary), but it will mean that SortFoo will have to clear the cache after each sorting (to avoid memory leak, and I do want the value to be recalculated on each SortFoo call).
Is there a cleaner and more elegant solution to this problem?
Because each item is compared against other items multiple times in a sort, you can cheaply cache the computation at least one-per-item.
If you’re often running the calculation against the same values, Memoizing the function would be your best bet,
This will reduce the calculations to once per item