Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple string replace performance [duplicate]

Tags:

c#

I am developing web application using C#. I want to replace multiple character in a string. For example,

string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-");
str = str.Replace("|",", ");
str = str.Replace(":",". ");

OR

string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-").Replace("|",", ").Replace(":",". ");

The above are the sample coding, actually I want to replace more characters. Is there any performance related issue in above two codes?

This may be a duplicate question, I searched for that, but I didn't find...

Thanks

like image 581
Jesuraja Avatar asked Nov 06 '25 12:11

Jesuraja


1 Answers

The two examples you provided are the same as each other.

Now, string replacing in general depends entirely on your use case. For example, this won't be a big performance hit:

string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
str = str.Replace("_","-").Replace("|",", ").Replace(":",". ");

...but this will be:

for (var i = 0; i < 100000; i++) {
    string str = "abc_def|ghij_klmn:opq|rst:uv_wx|yz";
    str = str.Replace("_","-").Replace("|",", ").Replace(":",". ");
}

If the latter type of operation is what you're after, I would suggest using a StringBuilder, since it will modify its internal structures directly (instead of immutable strings):

var sb = new StringBuilder(str);

...and chain Replace calls from there.

Alternatively, if that still doesn't provide you with the perf you require you can always look into unsafe code.. but that takes a whole different level of energy and understanding.

like image 121
Simon Whitehead Avatar answered Nov 09 '25 01:11

Simon Whitehead