Don't use foreach over MatchCollection, use for. UPDATED

UPDATE. Apparently they both call GetMatch(). So my advice isn't correct. Thanks 'Reflector' for the comment. What surprises me though is that first my routine (checked with Ants profiler) was slow because of the foreach, and now it's not.

Simple performance tip. Consider this code:

MatchCollection matches = myRegExp.Matches(someString);
foreach(Match m in matches)
{
    // your code which uses the match

This will perform awful. The reason is that the enumerator in MatchCollection executes the regexp again. This is, I guess, because you then can enumerate over the matchcollection without calling Matches. Instead do:

MatchCollection matches = myRegExp.Matches(someString);
for(int i=0;i<matches.Count;i++)
{
    Match m = matches[i];
    // your code which uses the match

4 Comments

  • 'Reflector' Hmmm :! indeed... How odd. the profiler showed a terrible slow foreach performance and now it's fast. Very odd.

  • Maybe you were reading the profiler results wrong and it was just the case that the rest of your code was so incredibly fast that the only bottleneck was the act of iterating.

    Wow, you are good! :)

  • Codesniper: haha :D

    What I think what caused this was the fact that in the routine where I used this code I also created the regex every time the routine was called. This was also slow, so I moved that to a static variable (regex's are thread safe anyway) so it might be that THAT move caused the sped up. I'll see if replacing the for with a foreach again in the new routine setup still gives a performance decrease.

  • Argh, I just changed all my code from foreach to for!!! Now I have to change it back? Frans, you tricked me!

    . j/k :)

Comments have been disabled for this content.