3 ms·
> But [the strcmp] is there, and a string comparison will usually (but not always) require comparing each of the characters in the string with the ones in the o
by gizmo 2y ago
> But [the strcmp] is there, and a string comparison will usually (but not always) require comparing each of the characters in the string with the ones in the other string
This is not true in anything except for toy interpreters, for a number of reasons.
One, internally strings are stored alongside the length. For 'TOP' and 'BOTTOM' the lengths don't match which means the strings can't be equal. That means inequality testing requires only a single integer comparison.
Two, strcmp is used for ordering strings, that's why it returns -1, 0, 1. That additional work isn't needed for testing equality. JS engines are not going to call strcmp unnecessarily.
Three, modern Javascript engines don't treat all strings the same. There are fast paths for ASCII strings, for interned strings, for concatenated strings, for strings that are slices of other strings, and more. From the perspective of the programmer a Javascript string is just a string. In reality a string in Javascript is nothing like C's char*.
I suspect -- but don't actually know -- that the string compare in the benchmark of example 1 is slower because the JS engine has to do a type check on the internal string representation. That's an extra branch the integer path doesn't need.
- kevingadd 2y agoThe string comparison probably involves more pointer chasing, which is going to hurt even if it doesn't have to type check.