Fastest: Substring or IndexOf

  • Thread starter Thread starter Chizl
  • Start date Start date
C

Chizl

If I know what the first 12 bytes of a string is, which would be faster to
validate those first 12 bytes?

if(szText.Substring(0,12) == "datagoeshere")
or
if(szText.IndexOf("datagoeshere")==0)
 
If I know what the first 12 bytes of a string is, which would be faster
to
validate those first 12 bytes?

if(szText.Substring(0,12) == "datagoeshere")
or
if(szText.IndexOf("datagoeshere")==0)

Well, which one is faster when you write a simple test application and
test it yourself? Doing that is the only way anyone here would be able to
answer your question with certainty.

It's also not an apples-to-apples comparison. Again, haven't done the
test myself, so this is a guess, but...I suspect one will (on average) be
faster if you normally have a match (IndexOf), the other will be faster if
you usually don't have a match (Substring).

You can probably get the best of both worlds by using this:

if (szText.IndexOf("datagoeshere", 0, 12) == 0)

This allows you to avoid having to create a new string instance, but also
prevents IndexOf from bothering to look at the rest of the string if the
search string isn't found right at the beginning.

Pete
 
This allows you to avoid having to create a new string instance, but also
prevents IndexOf from bothering to look at the rest of the string if the
search string isn't found right at the beginning.

Pete

Doesn't IndexOf stop after the first one is found?
 
Doesn't IndexOf stop after the first one is found?

Yes it does. With that in mind it would be even faster (although probably
immeasurable) to use String.StartsWith() so that it doesn't bother looking
past the first char if it's not a match.
 
Doesn't IndexOf stop after the first one is found?

Yes. But where would it stop if none is found? Why do you think that I
wrote in my previous post that on average, Substring() would be faster if
the search string is usually not part of the string?
 
Chizl said:
If I know what the first 12 bytes of a string is, which would be faster to
validate those first 12 bytes?

if(szText.Substring(0,12) == "datagoeshere")
or
if(szText.IndexOf("datagoeshere")==0)

IndexOf would inspect the entire string if your target is not found, so you
would not want that if you know ahead of time which part of the string you need
to look at. I would think that
if (szText.StartsWith("datagoeshere"))
would be your best bet if you know you are looking only at the first few bytes.

HTH,
-rick-
 

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

Back
Top