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

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.
 
A

Andrew Faust

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
 
T

Tom Overton

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top