Skip to content

Instantly share code, notes, and snippets.

@JimBobSquarePants
Created February 4, 2015 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JimBobSquarePants/35fd1cc71b4372c6ce06 to your computer and use it in GitHub Desktop.
Save JimBobSquarePants/35fd1cc71b4372c6ce06 to your computer and use it in GitHub Desktop.
Possible performance improvement in descendents.
internal static IEnumerable<IPublishedContent> EnumerateDescendants(this IPublishedContent content, bool orSelf)
{
if (orSelf) yield return content;
Stack<IPublishedContent> nodes = new Stack<IPublishedContent>(new[] { content });
while (nodes.Any())
{
IPublishedContent node = nodes.Pop();
yield return node;
// Preserve order.
foreach (IPublishedContent child in node.Children.Reverse())
{
nodes.Push(child);
}
}
}
@JimBobSquarePants
Copy link
Author

The reason is because a new IEnumerable would have to be created for each IPublishedContent visited if you used the call stack by recursively calling the method that gets the descendants - That would be inefficient. You should be able to significantly improve the traversal by using your own stack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment