Created
February 4, 2015 12:38
-
-
Save JimBobSquarePants/35fd1cc71b4372c6ce06 to your computer and use it in GitHub Desktop.
Possible performance improvement in descendents.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.