Reputation: 3555
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.
Upvotes: 22
Views: 3299
Reputation: 70652
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
Upvotes: 38