tags:

views:

359

answers:

2

Hi all, I need to replace all system. environment.newline (s) in the string returned by my function with "System.Environment.Newline + \t" (i'm trying to apply indenting) and I need to do this several times . now my question is which one is the fastest way to do this ? I know that stringbuilder is faster than string.replace but I dont know about regex.replace

thanks all

+1  A: 

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
A: 

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 Rozendo