Does String.Replace() create a new string if there's nothing to replace?

女生的网名这么多〃 提交于 2019-12-10 00:53:32

问题


For example:

public string ReplaceXYZ(string text)
{
    string replacedText = text;

    replacedText = replacedText.Replace("X", String.Empty);
    replacedText = replacedText.Replace("Y", String.Empty);
    replacedText = replacedText.Replace("Z", String.Empty);

    return replacedText;
}

If I were to call "ReplaceXYZ" even for strings that do not contain "X", "Y", or "Z", would 3 new strings be created each time?

I spotted code similar to this in one of our projects. It's called repeatedly as it loops through a large collection of strings.


回答1:


It does not return a new instance if there is nothing to replace:

string text1 = "hello world", text2 = text1.Replace("foo", "bar");
bool referenceEqual = object.ReferenceEquals(text1, text2);

After that code executes, referenceEqual is set to true.

Even better, this behavior is documented:

If oldValue is not found in the current instance, the method returns the current instance unchanged.

Otherwise, this would be implementation-dependent and could change in the future.

Note that there is a similar, documented optimization for calling Substring(0) on a string value:

If startIndex is equal to zero, the method returns the original string unchanged



来源:https://stackoverflow.com/questions/27052695/does-string-replace-create-a-new-string-if-theres-nothing-to-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!