Is the Javascript String length constant time?

后端 未结 6 2157
萌比男神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:57

    Length is an instance property and it's constant time

    It must be implement a string with a given length that is represented as a contiguous, zero-terminated array of jschars. It does this by explicitly storing a length and a pointer to the zero-terminated array

    Explicitly stored is the indicator here that it's constant time.

    Read How Strings Are Implemented In SpiderMonkey for more info on how Firefox implements strings.

提交回复
热议问题