Search code examples
javascriptstringperformancestring-comparison

What is the fastest way to compare strings in JavaScript?


I have two strings and I need to know whether they are equal.

I have previously done this: str1 === str2 , but I wonder if there is a faster way to compare two strings.

The strings are fairly short being 15-25 characters long. My problem is that I am iterating through a lot of strings and it is taking quite a long time.

I have a lot of comparisons in a structure like this:

If(str === str1)
{
  do something
}
else if(str === str2)
{
  do something
}
else if(str === str3)
{
  do something
}

The strings do not have any common structure or grouping.


Solution

  • Comparing strings with a === b is the fastest way to compare string natives.

    However, if you could create String Objects like new String("test"), re-use those and use those in the comparisons, that would be even faster, because the JS engine would only need to do a pointer-comparison, which is (a small amount) faster than string comparisons.

    See http://jsperf.com/string-vs-object-comparisons