简体   繁体   中英

Is isprefix more expensive than comparing two strings in C#?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM