2

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.

Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118
Asha
  • 3,871
  • 7
  • 44
  • 57
  • 1
    Already benchmarks by Debugging Toolbox http://blogs.msdn.com/debuggingtoolbox/archive/2008/04/02/comparing-regex-replace-string-replace-and-stringbuilder-replace-which-has-better-performance.aspx – Shay Erlichmen Oct 25 '09 at 09:06
  • Thanks Shay due to the benchmark sting.replace is the best one . PS : if somebody wants t read the article I suggest read all comments cause they didn't do a correct test at first place . – Asha Oct 25 '09 at 09:54

2 Answers2

15

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

Compiled Regex will be faster, however, unless the string is massive and is being run on a myriad of strings, String.Replace() is the way to go for the sake of readability.

Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118