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
length() is constant time operation in Java because length is stored as a field in String class.
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.
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.
length is a property of arrays in JavaScript that returns or sets the number of elements in a given array.
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.
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