DevEstacion
DevEstacion

Reputation: 1967

Should i use Regex.IsMatch before running Regex.Replace

I'm trying to use regex and regex does have its performance downside even if it's compiled.

What i want to know is, before actually running the Regex.Replace should i check first if there's a match in the string using Regex.IsMatch?

This question is about optimization and performance.

Upvotes: 2

Views: 859

Answers (1)

James Thorpe
James Thorpe

Reputation: 32202

As per my comment, performance questions are usually answered by trying it in your environment and measuring it objectively. However, this is quite defined, and based on a hunch of the replacement having to do a match anyway, we can go and inspect the source code. We see that within the Replace method, the very first thing it does after checking the arguments is to perform a match:

match = regex.Match(input, startat);

Which shows that yes, it's probably a waste of time to check if there's a match before doing the replace.

Upvotes: 5

Related Questions