does string.length calculate length on calling string.length

Viewed 174

Recently i came to know the time complexity for string.length in javascript is 0(1). is there any one who can make me understand why as to get the length we need to go through all the characters and if the string having n characters then it should depend on the n and should cost us 0(n).

I would really appreciate if someone can clear this or can send link for the native implementation of string.length

Thanks in advance :-)

2 Answers

This is because string is immutable,so the length is calculated when string is created and it will never change.

When a string is modified, a new string object will be created and so length.

So length is constant time O(1).

String is a class. A class can have member variables and functions. When you create a string the length member variable is probably set. There's probably a "hidden" function that runs O(n) for the initialising of the string but once the length is set, the computer need only access the value, so O(1). This is all predefined and the programmer need only know how to use the function.

Related