Is isprefix more expensive than comparing two strings in C#? – Education Career Blog

I’m doing some calculations of comparing two strings. In case I know they are same length, is it more expensive to call isprefix or If (“string”==”string”) ?

,

Why not test? Easy enough to use the StopWatch class to compare, and include different length strings and different compare options.

I would expect no significant difference at the core, as IsPrefix is essentially:

public bool IsPrefix(string comp, string prefix) {
  return Compare(comp, 0, prefix.Length, prefix, 0, prefix.Length);
}

However there may be a difference between String’s operator == and CompareInfo class due to level of I18N applied.

In the end, you will need to measure, but I would expect that 99% of cases any difference is not significant to the overall application performance.

,

I would assume the equality operator actually compared the two strings hash values, rather than the actual content (at least as a fail-fast)

Since the prefix matching would require a substring creation before hash value comparison then it follows that prefix matching should be much slower than full equality matching.

If you have enough strings you need to prefix match, you should look into implementing a TRIE structure (http://paste.lisp.org/display/12161)

Leave a Comment