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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With