简体   繁体   中英

string.Replace or stringBuilder.Replace()

I'm new to C#, so please forgive me my mistakes.

I want to replace some part of a string, every time that piece of code is called (2-4 times per call). I was wondering which method is better to use in terms of performance: string.Replace or stringBuilder.Replace() ?

What if this piece of code is called 10.000 times concurrently??

The best way to find out which one is faster is to benchmark it for your particular problem - write a simple test harness and time the two options.

Having said that - C# strings are immutable , which means you can't change them after they are created. When you call String.Replace the runtime has to create a new String instance for the result. This means that a sequence of changes to the same string will be slow, because the runtime has to create a new object for each manipulation, allocating memory and copying the string data each time.

StringBuilder was specifically designed as a mutable string for this type of situation - to avoid creating a new String instance on each manipulation.

So StringBuilder will almost certainly be faster if you're doing a sequence of Replace calls on the same string.

Use String.Replace() after your string is made,it will replace at all the places at once. it would be Better if you explain your scenario with some example.

Look at this link it has a good description: Comparing RegEx.Replace, String.Replace and StringBuilder.Replace – Which has better performance?

String Replace is different from StringBuilder Replace. But on the surface they are the same. StringBuilder is purely an optimization, but considering the prevalence of string usage, it is critical. String.Replace always creates a new string – StringBuilder.Replace doesn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM