次の方法で共有


How to traverse xmlelement.childnodes effectively

I have been working on the performance these days, and I want to share some tricks that you can do to reduce memory allocation significantly if the xml document you are working with is huge.

Use XmlElement.FirstChild and next sidbling is a lot cheaper than foreach(xmlnode child in element.ChildNodes).  You can run the CLRProfiler to see the difference.

         // index approach -- bad 
        static int Approach1(XmlNode element)
        {
            int count = 1;

            for ( int index = 0; index < element.ChildNodes.Count; index++ )
            {
                XmlElement child = element.ChildNodes[index] as XmlElement;

                if ( child != null )
                    count += Approach1(child);
            }

            return count;
        }

        // foreach approach: -- bad
        static int Approach2(XmlNode element)
        {
            int count = 1;

            foreach ( XmlNode node in element.ChildNodes )
            {
                if ( node is XmlElement )
                {
                    count += Approach2(node);
                }
            }

            return count;
        }

        // first child + sibling approach -- good
        static int Approach3(XmlNode element)
        {
            int count = 1;

            XmlNode child = element.FirstChild;

            while( child != null && child is XmlElement)
            {
                count += Approach3(child);
                child = child.NextSibling;               
            }           

            return count;
        }

Hope this helps!