Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is javascript str.length calculated every time it is called or just once?

Tags:

javascript

Which way is more efficient? Is there a difference?

This one:

var str = 'abc';

if(str.length == 20) {
    //...
}

if(str.length == 25) {
    //...
}

// and so on

Or this one:

var str = 'abc';
var length = str.length;

if(length == 20) {
    //...
}

if(length == 25) {
    //...
}

// and so on
like image 368
Silver Light Avatar asked May 24 '11 14:05

Silver Light


People also ask

Is string length constant time JS?

length() is constant time operation in Java because length is stored as a field in String class.

How does JavaScript length work?

The length property of an Array object represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Is string length a function or a property JavaScript?

Length is not a method, it is a property. It doesn't actually do anything but return the length of an array, a string, or the number of parameters expected by a function. When you use . length, you are just asking the JavaScript interpreter to return a variable stored within an object; you are not calling a method.

What does length return in JavaScript?

length is a property of arrays in JavaScript that returns or sets the number of elements in a given array.


1 Answers

In the browsers where this might actually matter (read: IE) it will be calculated every time, so it's faster to store the value in a local variable.

http://jsperf.com/string-length


It used to be that

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

was faster than

for (var i=0; i<someArray.length; i++) {
    // ...
}

but these days, V8's (Chrome's JS engine) optimizes the latter to run faster than the former. That's great - just remember, you don't really need to worry about performance in Chrome.


If you're curious to learn more about JavaScript performance, High Performance JavaScript is a solid read. Take its recommendations with a grain of salt, though, since a trick that makes code run faster in IE (6, 7, 8 or even 9) might very well make the code run slower in Chrome or Firefox 4.

like image 194
Matt Ball Avatar answered Oct 10 '22 13:10

Matt Ball