如果没有替代内容,String.Replace()是否会创建一个新字符串? [英] Does String.Replace() create a new string if there's nothing to replace?
问题描述
例如:
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;
}
如果即使对于不包含"X","Y"或"Z"的字符串也要调用"ReplaceXYZ",那么每次都会创建3个新字符串吗?
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.
推荐答案
如果没有可替换的内容,它不会返回新实例:
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);
执行该代码后,将referenceEqual
设置为true
.
After that code executes, referenceEqual
is set to true
.
更好的是,此行为已记录:
如果在当前实例中未找到oldValue,则该方法将不变地返回当前实例.
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.
请注意,有类似的记录了针对string
值调用Substring(0)
的优化:
Note that there is a similar, documented optimization for calling Substring(0)
on a string
value:
如果startIndex等于零,则该方法不变地返回原始字符串
If startIndex is equal to zero, the method returns the original string unchanged
这篇关于如果没有替代内容,String.Replace()是否会创建一个新字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!