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

前端 未结 12 1528
孤街浪徒
孤街浪徒 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:35

    When you declare:

    var s = '0123456789';
    

    you create a string primitive. That string primitive has methods that let you call methods on it without converting the primitive to a first class object. So your supposition that this would be slower because the string has to be converted to an object is not correct. It does not have to be converted to an object. The primitive itself can invoke the methods.

    Converting it to an full-blown object (which allows you to add new properties to it) is an extra step and does not make the string oeprations faster (in fact your test shows that it makes them slower).

提交回复
热议问题