Should I use string.Contains() before string.Replace()?

I know this is an old thread, but just wanted to provide my 2¢!

Please, let me know if what I'm saying is wrong, but I just tried it on my environment and seemed plausible! :)

For the most part, yes, the replace function will do the contains for you therefore it's unnecessary to have it separately. However, it is advantageous to do so if your "new value" is derived from a method - depending on how much work is done to get that value within the method!

Example when it not advantageous: I'm working on making "String Replacers" for the body of an email sent by an application. For example, if the user has "[[User Name]]" within the body of the email, I want to replace that with the recipients first name. Thankfully, our framework has that information stored in memory, so I don't mind doing a single replace for that.

Example when it is advantageous: Under the same premise from above, another replacer is "[[Payments]]". This would go to the database, and bring up a log of the top 1000 transactions the user made, then do some work on the data retrieved and show details on the body of the email. Imagine having to do all of that every time the user sends an email from the app, even if it doesn't contain the "[[Payments]]" keyword! Having the contains before calling my method that comes up with the string value of "[[Payments]]" really pays off here!

Long story short, it depends on your implementation, but for the most part - yes, it's unnecessary.


Since the String.Replace() function doesn't throw an exception if the string doesn't contain the value specified, it's unnecessary to verify it. It will go through an unnecessary condition.


All the details are in the documentation for String.Replace:

Return Value:
A string that is equivalent to the current string except that all instances of oldValue are replaced with newValue. If oldValue is not found in the current instance, the method returns the current instance unchanged.

The if statement is not required.

An if statement is not even a performance optimization, since String.Replace returns the same object instance, if oldValue is not found. I have verified this using the following code:

namespace StringReplaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "Test";
            string s2 = s.Replace("Foo", "Bar");
            string s3 = s.Replace("es", "tt");
        }
    }
}

Using the handy Make Object ID feature (right-click on a symbol in the Locals, Auto, or Watch window; see Common Expression Evaluator Features for more details) produced the following output:

s  | "Test" {$1}
s2 | "Test" {$1}
s3 | "Tttt" {$2}

Tags:

C#

.Net