Frans Bouma's blog

Generator.CreateCoolTool();

Syndication

News

    Visit LLBLGen Pro's website

    Follow FransBouma on Twitter

    Add to Technorati Favorites

About me

Fun stuff I created

My work

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

Published Thursday, June 07, 2007 4:45 PM by FransBouma

Filed under: ,

Comments

# re: Don't use foreach over MatchCollection, use for@ Thursday, June 07, 2007 12:15 PM

I suggest you break out Reflector, because they both call MatchCollection.GetMatch internally. This is bad advice, Frans.

Reflector

# re: Don't use foreach over MatchCollection, use for. UPDATED@ Thursday, June 07, 2007 12:38 PM

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

FransBouma

# re: Don't use foreach over MatchCollection, use for. UPDATED@ Thursday, June 07, 2007 4:46 PM

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

# re: Don't use foreach over MatchCollection, use for. UPDATED@ Friday, June 08, 2007 3:29 AM

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.

FransBouma

# re: Don't use foreach over MatchCollection, use for. UPDATED@ Wednesday, June 13, 2007 8:56 PM

Argh, I just changed all my code from foreach to for!!! Now I have to change it back? Frans, you tricked me! . j/k :)

anon