Is the Javascript String length constant time?

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

    In any language that has immulate strings, whether Java, JavaScript, C# or others, it will be a very bad practice by the creators of the language NOT to provide a "constant time" "length" operation for a string.
    Since the string is immutable, its length cannot change, hence all it is required is to store the length of the string upon creation in some field inside the string object and return it upon calling to the "length" propery/method.

提交回复
热议问题