Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 661
Jake Shakesworth Avatar asked Nov 21 '14 01:11

Jake Shakesworth


People also ask

Does string replace create a new string?

Java String replace() method replaces every occurrence of a given character with a new character and returns a new string. The Java replace() string method allows the replacement of a sequence of character values.

What does the replace () method do?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

How do I replace a string without replacing it?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.

Does replace modify the original string?

The Basics of Replacing a String JavaScript strings are immutable, so the String#replace() function returns the modified string. It does not modify the existing string. Generally, the first argument to replace() is called the pattern, and the 2nd argument is called the replacement.


1 Answers

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

like image 79
Peter Duniho Avatar answered Sep 20 '22 12:09

Peter Duniho