I test 2 loops with the same values and code:
1) For loop:
for (int i = 0; i < MyGlobals.check1Count; i++)
{
addToMyGlobals(root2.SelectNodes(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.