Is the Javascript String length constant time?

后端 未结 6 2159
萌比男神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 21:01

    Strings are also immutable in JavaScript. The length property does not need to be computed each time it is accessed.

    I created a jsperf benchmark for you to view here.

    You'll notice the speeds are the same.

提交回复
热议问题