I want to compare two strings in JavaScript to test if they are exactly the same. Which would be the best (fastest) way to do this?
Right now, I'm considering either
if(string1.localeCompare(string2) == 0) {}
or simply
if(string1 == string2)
Is there a better way do to this?
Explanation of the example: In the above example, when str1 and str2 are compared after using the toUpperCase method, the expression JAVASCRIPT == JAVASCRIPT would return true as they are the same strings after both being in upper case. Here, the equality operator (==) is used to check if both the strings are the same.
The localeCompare() method compares two strings in the current locale. The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).
String equality is slightly faster at 13.15ms vs BigInt at 16.57ms for 100k comparisons.
I would probably use strict equality if you want to check they are exactly the same, ie they're the same type too, just in case.
if (string1 === string2)
Check this fiddle* and figure out yourself which one is faster.
*In case the link dies in the future: ==
> ===
> String.localeCompare
(tested on Chrome).
I'm not sure there is any room to optimize if(string1 == string2)
. That is the best approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With