String.Replace Performance

J

Jay Ayliff

I have to do a series of about twenty string.replace operations on a long
string, like this:

BigString = BigString.Replace(FromText, ToText)

BigString won't contain FromText every time, but I can't tell in advance
which ones are there and which are not.

My question is this: Am I better off just doing the replace operation each
time, or will it be more performant to check for the existence of the
'FromString' like this:

If InStr(BigString, FromText, CompareMethod.Text) > 0 Then
BigString = BigString.Replace(FromText, ToText)

No doubt there's a break-even point depending on how many String.Replace
operations get saved, but is String.Replace more expensive than InStr? Is
String.Replace still expensive if it doesn't find anything to replace?

The code is in a part of the application where I need it to be as quick as
possible. Do any of you framework experts have a rule of thumb that would
help me?

Regards

Jay Ayliff
Stalis Ltd
 
J

Jon Skeet [C# MVP]

Jay Ayliff said:
I have to do a series of about twenty string.replace operations on a long
string, like this:

BigString = BigString.Replace(FromText, ToText)

BigString won't contain FromText every time, but I can't tell in advance
which ones are there and which are not.

My question is this: Am I better off just doing the replace operation each
time, or will it be more performant to check for the existence of the
'FromString' like this:

If InStr(BigString, FromText, CompareMethod.Text) > 0 Then
BigString = BigString.Replace(FromText, ToText)

No doubt there's a break-even point depending on how many String.Replace
operations get saved, but is String.Replace more expensive than InStr? Is
String.Replace still expensive if it doesn't find anything to replace?

The code is in a part of the application where I need it to be as quick as
possible. Do any of you framework experts have a rule of thumb that would
help me?

Have you considered using StringBuilder.Replace instead? Construct a
StringBuilder from your original string, do the replacements, and then
convert it back to a string. That should avoid creating too much more
objects.

A quick test suggests that String.Replace doesn't create a new string
if it doesn't find anything to 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