Delen via


Which is faster: Regex.IsMatch or String.Contains?

This blog has moved. An updated version of this post is available here.

Comments

  • Anonymous
    June 03, 2010
    Did you try Regex.Compile? msdn.microsoft.com/.../8zbs0h2f(VS.71).aspx

  • Anonymous
    June 03, 2010
    The comment has been removed

  • Anonymous
    June 22, 2010
    Sure. But if you're using RegexOptions.Compiled then IsMatch is actually faster. Try putting: Regex nulla = new Regex("nulla", RegexOptions.Compiled); s.Start(); //Normally we have a static Regex so it isn't fair to time the initialization (although it doesn't make a difference in this case) for (int i = 0; i < trials; i++) {  bool isMatch = nulla.IsMatch(message); } I got: regex =      00:00:00.6902234 contains = 00:00:00.8815885 (during 10 trials it was consistently faster) Lesson must be that if you're searching for the same thing a lot, the dynamically compiled state machine provided by RegexOptions.Compiled is actually faster. Even if just searching for a simple string.