Why Javascript ===/== string equality sometimes has constant time complexity and sometimes has linear time complexity?

后端 未结 3 1537
一个人的身影
一个人的身影 2020-12-31 20:37

After I found that the common/latest Javascript implementations are using String Interning for perfomance boost (Do common JavaScript implementations use string interning?),

相关标签:
3条回答
  • 2020-12-31 21:13

    According to the ECMAScript 5.1 Specification's Strict Equal Comparison algorithm, even if the type of Objects being compared is String, all the characters are checked to see if they are equal.

    1. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.

    Interning is strictly an implementation thingy, to boost performance. The language standard doesn't impose any rules in that regard. So, its up to the implementers of the specification to intern strings or not.

    0 讨论(0)
  • 2020-12-31 21:18

    Based on all the Performance Tests (see original post) for strings a and b the operation a === b takes:

    • constant time O(1) if the strings are interned. From the examples it seems that interning only happens with directly assigned strings like var str = "test"; and not if you build it with concatenation using for-loops or functions.

    • linear time O(N) since in all the other cases the length of the two strings is compared first. If it is equal then we have character by character comparison. Else of course they are not equal. N is the length of the string.

    0 讨论(0)
  • 2020-12-31 21:27

    First of all, it would be nice to see a JSPerf test which demonstrates the claim that doubling the string size doubles the execution time.

    Next, let's take that as granted. Here's my (unproven, unchecked, and probably unrelated to reality) theory.

    Compairing two memory addresses is fast, no matter how much data is references. But you have to INTERN this strings first. If you have in your code

    var a = "1234";
    var b = "1234";
    

    Then the engine first has to understand that these two strings are the same and can point to the same address. So at least once these strings has to be compared fully. So basically here are the following options:

    • The engine compares and interns strings directly when parsing the code. In this case equals strings should get the same address.
    • The engine may say "these strings are two big, I don't want to intern them" and has two copies.
    • The engine may intern these strings later.

    In the two latter cases string comparison will influence the test results. In the last case - even if the strings are finally interned.

    But as I wrote, a wild theory, for theory's sage. I'd first like to see some JSPerf.

    0 讨论(0)
提交回复
热议问题