tags:

views:

218

answers:

4

This is a followup to this question

The first two answers are both correct and complete and at the end of the day, produce exactly the same result. However, one uses a Regex object and calls the aRegex.Replace(...) method (Joel's answer) and the other uses the static Regex.Replace(...) method. (CMS' answer).

Which method is preferred?
Under what circumstances would you change your mind?

+1  A: 

Using the regex object means the regex is compiled only once, so you get better performance (you need to save the regex object someplace).

orip
+3  A: 

Using the static instance will create a new Regex object each time so it is better to instantiate it yourself. Here is what I found using Reflector on System.dll:

public static string Replace(string input, string pattern, string replacement)
{
    return new Regex(pattern, RegexOptions.None, true).Replace(input, replacement);
}

Plus if you instantiate your own instance you will be able to compile it as well and improve performance for multiple uses.

You can send RegexOptions.Compiled to one of the static Replace overloads but this is pointless as the Regex object that will be instantiated with this flag cannot be used again.

Andrew Hare
The reflector really made it clear. Only use the static for a genuine one-off.
chris
A: 

aRegex.Replace(...) would be preferred if you can reuse it

BlackTigerX
A: 

It's not as inefficient as it looks. Going into the Regex constructor with reflector, it caches the compiled regex code. That's probably the most time-consuming part.

I would generally use Regex.Replace() initially because it's more convenient and only change if it there's a performance problem.

Also you could write extension methods on string for convenience, eg:

public static string RegexReplace(this string source, string pattern, string replacement)
{
    return Regex.Replace(source, pattern, replacement);
}
The reflector shows that the static method constructs a Regex object anyways. There appears to be no performance advantage to using the static over constructing your own object. It just appears to be useful as a shorthand for one-offs.
chris