2

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.

2
  • 2
    The answer to most performance questions is "try it in your environment, measure it objectively and see". However in this case, I'd guess that it's a waste of time to find out if a regex matches before doing a replace, as the first thing it's going to have to do in the replace is match it again anyway. Commented Mar 19, 2015 at 9:46
  • 1
    My guess would be no, calling Regex.IsMatch before Regex.Replace would actually slow down the execution. But since you have the code why not test it to make sure? Commented Mar 19, 2015 at 9:46

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.