使用字符串+字符串+字符串VS使用与string.replace字符串、VS、replace、string

2023-09-06 06:25:33 作者:蓝颜∨妖精

一个同事告诉我,使用下面的方法:

A colleague told me that using the following method:

 string url = "SomeURL";
 string ext = "SomeExt";
 string sub = "SomeSub";
 string subSub = "moreSub";
 string Url = @"http://www." + Url +@"/"+ ext +@"/"+  sub  + subSub;

不efficenet(需要更多的资源),它是pferred使用下面的方法$ P $:

is not efficenet (takes more resources) and it is preferred to use the following method:

 string Url = @"http://www.#URL.#EXT/#sub/#subSub";
 string url = "SomeURL";
 string ext = "SomeExt";
 string sub = "SomeSub";
 string subSub = "moreSub";
 Url = Url.Replace("#URL",url)
 Url = Url.Replace("#EXT",ext);
 Url = Url.Replace("#sub",sub);
 Url = Url.Replace("#subSub",subSub);

是这样吗?什么是其背后的解释?

Is that true? and what is the explanation behind it?

我读这答,它让我想知道有关这个案子的:

I read this Answer and it got me wondering what about this case :

 string Url = @"http://www.#URL.#EXT/#sub/#subSub";
 string url = "SomeURL";
 string ext = "SomeExt";
 string sub = "SomeSub";
 string subSub = "moreSub";
string finalUrl = new StringBuilder(Url )
        .Replace("#URL", "URL")
        .Replace("#EXT", "EXT")
        .Replace("#sub", "sub")
        .Replace("#subSub", "subSub")
        .ToString();

是,更多的efficenet然后??

is that more efficenet then ??

推荐答案

您的同事是的完全的错误。

他被错误应用的事实,字符串是不可变的,并且追加两个字符串将创建第三个字符串对象。 你的方法( A + B + C )是最有效的方法来做到这一点。 编译器可以将您的code到呼叫 String.Concat(字符串[]),它使用不安全code分配一个缓冲区所有的串并复制到缓冲区中。

He is mis-applying the fact that strings are immutable, and that appending two strings will create a third string object. Your method (a + b + c) is the most efficient way to do this. The compiler transforms your code into a call to String.Concat(string[]), which uses unsafe code to allocate a single buffer for all of the strings and copy them into the buffer.

他的建议应该是在一个循环连接字符串时,使用StringBuilder。

His advice should be to use a StringBuilder when concatenating strings in a loop.

修改: String.Concat (相当于 + 串联,像你的第一个例子)就是这样做的最快方法。使用像在你编辑一个StringBuilder会慢一些,因为它将需要在每次更换通话过程中调整字符串。

EDIT: String.Concat (which is equivalent to + concatenation, like your first example) is the fastest way to do this. Using a StringBuilder like in your edit will be slower, because it will need to resize the string during each Replace call.