You can get a noticeable improvement in this case if you don't use a compiled regex. Honestly, this isn't the first time I measure regex performance and find the compiled regex to be slower, even if used the way it's supposed to be used.
Let's replace \bfast\b
with 12345
in a string a million times, using four different methods, and time how long this took - on two different PCs:
var str = "Regex.Replace is extremely FAST for simple replacements like that";
var compiled = new Regex(@"\bfast\b", RegexOptions.IgnoreCase | RegexOptions.Compiled);
var interpreted = new Regex(@"\bfast\b", RegexOptions.IgnoreCase);
var start = DateTime.UtcNow;
for (int i = 0; i < 1000000; i++)
{
// Comment out all but one of these:
str.Replace("FAST", "12345"); // PC #1: 208 ms, PC #2: 339 ms
compiled.Replace(str, "12345"); // 1100 ms, 2708 ms
interpreted.Replace(str, "12345"); // 788 ms, 2174 ms
Regex.Replace(str, @"\bfast\b", "12345", RegexOptions.IgnoreCase); // 1076 ms, 3138 ms
}
Console.WriteLine((DateTime.UtcNow - start).TotalMilliseconds);
Compiled regex is consistently one of the slowest ones. I don't observe quite as big a difference between string.Replace
and Regex.Replace
as you do, but it's in the same ballpark. So try it without compiling the regex.
Also worth noting is that if you had just one humongous string, Regex.Replace is blazing fast, taking about 7ms for 13,000 lines of Pride and Prejudice on my PC.