开发者

for loop 5-6 times slower than foreach loop in HtmlAgility Pack

开发者 https://www.devze.com 2023-03-07 06:23 出处:网络
I test 2 loops with the same values and code: 1) For loop: for (int i = 0; i < MyGlobals.check1Count; i++)

I test 2 loops with the same values and code: 1) For loop:

for (int i = 0; i < MyGlobals.check1Count; i++)
{
addToMyGlobals(root2.Sel开发者_如何转开发ectNodes(strXPath)[i].OuterHtml.Trim(), XPathArrayIndex);
}

2) Foreach loop:

        foreach (HtmlNode link1 in root2.SelectNodes(strXPath))
        {
          addToMyGlobals(link1.OuterHtml.Trim(), XPathArrayIndex);
        }

And the results is that 'Foreach loop' is 5-6 times faster than the 'For Loop'. Why is that, what is happening, can somebody gives explanation about it?


In your for loop, you are executing the expensive SelectNodes() method on every iteration of the loop. The foreach loop only does this once.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号