Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Javascript String length constant time?

Tags:

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<str.length; i++){...}

vs

var len = str.length;
for (i=0; i<len; i++){...}

Now, I know str.length() is constant time operation in Java because length is stored as a field in String class. But then again, strings are immutable in Java. I am not sure about JS strings though. Is str.length guaranteed constant time in JS too? Couldn't find this discussed anywhere in the web.

like image 298
aalosious Avatar asked Jun 18 '15 21:06

aalosious


People also ask

Does string have length property in JavaScript?

In JavaScript, length is a string property that is used to determine the length of a string. Because length is a property of the String object, it must be invoked through a particular instance of the String class.

What is the length of string in JavaScript?

JavaScript does not return the length but rather returns the code units occupied by the string. It uses the UTF-16 string formatting methods to store characters. This essentially means that the characters in your string are encoded into a 16-bit long binary number before being stored.

How does length function work in JavaScript?

The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings.

What is JavaScript length?

length is a property of arrays in JavaScript that returns or sets the number of elements in a given array. The length property of an array can be returned like so. The assignment operator, in conjunction with the length property, can be used to set the number of elements in an array like so.


2 Answers

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.

like image 162
maček Avatar answered Oct 03 '22 13:10

maček


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.

like image 39
Bergi Avatar answered Oct 03 '22 13:10

Bergi