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?
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.
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.
The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With