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
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
was faster than
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.