# Make a recursive method faster

How would you refactor this method to make it more performant?

If you have refactored the code you need to prove the performance gain in numbers to get the solution :)

public static T Find<T>(
this IEnumerable<T> source,
Func<T, IEnumerable<T>> childrenSelector,
Predicate<T> condition)
{
T t = default(T);
foreach (T item in source)
{
if (condition(item))
{
return item;
}

t = childrenSelector(item).Find<T>(childrenSelector, condition);

if (!Equals(t, default(T)))
{
return t;
}
}
return t;
}

• How can one "prove the performance gain in numbers" if you do not give us a concrete example? Also: stackoverflow.com/tags/performance/info Good question states performance goals that need to be achieved as well as other restrictions. Trying to optimize something without measuring is not "performance" question or work, but most likely personal entertainment - expect question without goals/measurements to be treated as such. – ANeves Feb 29 '12 at 14:09
• use the method with a closed generic type and search a 100000 object tree for a certain items property value. Do the same with your optimization on the method then rerun the test. Compare both results and show them here. Thats about the numbers. :) – Pascal Feb 29 '12 at 22:39

I would thus not try to make the code faster, but the algorithm faster. If searching in a tree actually slows your code, that means you need to change the way it works so that you know which branch to explore at each function call and having O(log n) complexity instead of O(n)`. There are tons of trees which have nice properties likes this: B-trees, red-black trees, splay trees and so on. You can also consider using a hash table.