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

后端 未结 3 1545
一个人的身影
一个人的身影 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: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.

提交回复
热议问题