Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace, String.Replace or StringBuilder.Replace which is the fastest?

I need to replace all System.Environment.Newline(s) in the string returned by my function with System.Environment.Newline + \t (as I am trying to apply indenting) and I need to do this several times.

My question is which one is the most efficient way to do this?

I know that StringBuilder is faster than String.Replace but I dont know about Regex.Replace.

like image 314
Asha Avatar asked Apr 27 '26 11:04

Asha


1 Answers

If you're just trying to do it within a single string, I'd expect string.Replace to be as fast as anything else. StringBuilder is useful when you want to perform a number of separate steps and want to avoid creating an intermediate string on each step.

Have you benchmarked string.Replace to find out whether or not it's fast enough for you?

I would personally only start using regular expressions when I was actually dealing with a pattern, rather than just a fixed sequence of characters. If the performance of this is absolutely crucial, you could benchmark that as well of course.

like image 181
Jon Skeet Avatar answered Apr 29 '26 01:04

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!