Is the Javascript String length constant time?

后端 未结 6 2153
萌比男神i
萌比男神i 2020-12-18 20:15

I\'m fairly new to JS, and realize length is considered a property. But I received a comment to not use str.length in a loop:

for (i=0; i

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-18 20:51

    Is str.length guaranteed constant time in JS too?

    No, in fact there are no runtime performance or complexity guarantees in JavaScript whatsoever.

    However, yes, it can be expected to be accessible in constant time, with no dynamic linear time length computation on access. The ECMAScript spec also describes the String .length property as immutable and that it is initialised when the string is constructed.

提交回复
热议问题