Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Replace(char, char) or Replace(string, string)?

Is there a performance difference between String.Replace(char, char) and String.Replace(string, string) when I just need to replace once character with another?

like image 218
Laguna Avatar asked Feb 03 '12 14:02

Laguna


People also ask

How do I replace a character in a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

What is a replace string?

Definition and Usage The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

What is replace () in Python?

The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring.

What is the difference between Replace () and replaceAll ()?

The replaceAll() method is similar to the String. replaceFirst() method. The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string.


1 Answers

Yes, there is: I ran a quick experiment, and it looks like the string version is about 3 times slower.

    string a = "quickbrownfoxjumpsoverthelazydog";
    DateTime t1 = DateTime.Now;
    for (int i = 0; i != 10000000; i++) {
        var b = a.Replace('o', 'b');
        if (b.Length == 0) {
            break;
        }
    }
    DateTime t2 = DateTime.Now;
    for (int i = 0; i != 10000000; i++) {
        var b = a.Replace("o", "b");
        if (b.Length == 0) {
            break;
        }
    }
    DateTime te = DateTime.Now;
    Console.WriteLine("{0} {1}", t2-t1, te-t2);

1.466s vs 4.583s

This is not surprising, because the overload with strings needs an extra loop to go through all characters of the oldString. This loop runs exactly one time, but the overhead is still there.

like image 196
Sergey Kalinichenko Avatar answered Oct 06 '22 22:10

Sergey Kalinichenko