String.Contains then a String.Replace or just String.Replace

  • Thread starter Thread starter greatbarrier86
  • Start date Start date
G

greatbarrier86

What's the best practice suggestion for a situation like this? Should i check
to see if the string contains the specified To-Be-Replaced string before
actually executing String.Replace? Or is it better to just run Replace? It
sees more efficient to just do Replace, but more appropriate to do Contains
first.
 
greatbarrier86 said:
What's the best practice suggestion for a situation like this? Should i
check
to see if the string contains the specified To-Be-Replaced string before
actually executing String.Replace? Or is it better to just run Replace? It
sees more efficient to just do Replace, but more appropriate to do
Contains
first.

Just do the Replace. If the search string isn't found Replace doesn't do
anything. No reason to waste CPU cycles on unnecessary operations. It would
also be more confusing to add the Contains. Most .Net developers will know
the extra call to Contains is unnecessary and it will just confuse them as
to why it's there.

Andrew Faust
 
Hello greatbarrier86,
Actually it is better to use StringBuilder.Replace
It's usually preferrable to use StringBuilder due to it being mutable
but if you're just doing a simple replace on a single string (not to
bunch of strings) and the string is not very big you should just use
String.Replace. For a small string the extra overhead of creating a
new StringBuilder instance would probably equal or even exceed the
extra overhead of String creating a new String instance to hold the
result of the Replace.
 
Back
Top