2

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

Jesuraja
  • 3,774
  • 4
  • 24
  • 48
  • I found the similar question asking about the performance of `String.Replace();` please Check this one :http://stackoverflow.com/questions/399798/memory-efficiency-and-performance-of-string-replace-net-framework – Avinash patil May 16 '14 at 05:15
  • The two examples should have virtually the same performance. Writing the three method calls in one expression doesn't change the fact that you are scanning the string three times and creating interim string instances that are immediately eligible for garbage collection. – phoog May 16 '14 at 05:15

1 Answers1

2

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.

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138