What is the difference between string primitives and String objects in JavaScript?

前端 未结 12 1523
孤街浪徒
孤街浪徒 2020-11-22 07:58

Taken from MDN

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., witho

12条回答
  •  隐瞒了意图╮
    2020-11-22 08:27

    The code is optimized before running by the javascript engine. In general, micro benchmarks can be misleading because compilers and interpreters rearrange, modify, remove and perform other tricks on parts of your code to make it run faster. In other words, the written code tells what is the goal but the compiler and/or runtime will decide how to achieve that goal.

    Block 1 is faster mainly because of: var s = '0123456789'; is always faster than var s = new String('0123456789'); because of the overhead of object creation.

    The loop portion is not the one causing the slowdown because the chartAt() can be inlined by the interpreter. Try removing the loop and rerun the test, you will see the speed ratio will be the same as if the loop were not removed. In other words, for these tests, the loop blocks at execution time have exactly the same bytecode/machine code.

    For these types of micro benchmarks, looking at the bytecode or machine code wil provide a clearer picture.

提交回复
热议问题