简体   繁体   English

string.Replace或stringBuilder.Replace()

[英]string.Replace or stringBuilder.Replace()

I'm new to C#, so please forgive me my mistakes. 我是C#的新手,所以请原谅我的错误。

I want to replace some part of a string, every time that piece of code is called (2-4 times per call). 我想每次调用该段代码时都替换字符串的某个部分(每次调用2-4次)。 I was wondering which method is better to use in terms of performance: string.Replace or stringBuilder.Replace() ? 我想知道哪种方法在性能方面更适合使用: string.ReplacestringBuilder.Replace()吗?

What if this piece of code is called 10.000 times concurrently?? 如果这段代码被同时调用10.000次怎么办?

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. 话虽这么说-C#字符串是不可变的 ,这意味着创建它们后就无法更改它们。 When you call String.Replace the runtime has to create a new String instance for the result. 调用String.Replace ,运行时必须为结果创建一个新的String实例。 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. StringBuilder被专门设计为针对这种情况的可变字符串-避免在每次操作时创建新的String实例。

So StringBuilder will almost certainly be faster if you're doing a sequence of Replace calls on the same string. 因此,如果对同一字符串执行一系列Replace调用,则StringBuilder几乎可以肯定会更快。

Use String.Replace() after your string is made,it will replace at all the places at once. 生成字符串后,使用String.Replace() ,它将立即在所有位置替换。 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? 看一下这个链接,它有一个不错的描述: 比较RegEx.Replace,String.Replace和StringBuilder.Replace –哪个性能更好?

String Replace is different from StringBuilder Replace. String替换与StringBuilder替换不同。 But on the surface they are the same. 但从表面上看,它们是相同的。 StringBuilder is purely an optimization, but considering the prevalence of string usage, it is critical. StringBuilder纯粹是一种优化,但是考虑到字符串用法的普遍性,它至关重要。 String.Replace always creates a new string – StringBuilder.Replace doesn't. String.Replace始终创建一个新字符串StringBuilder.Replace不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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