开发者

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

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

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.


The second is by far the safer way to go. In the first you are assuming that it won't get recalculated. In the second you know that it won't. The second isn't always the best way though. It will only work when you know other processes won't affect the length of the array. So with global variables etc. you have to be careful. This can also apply to modifying the contents (length) of an array inside a for loop which stops at the upper bound of the array.


Strings are immutable in JavaScript, so it is unlikely that even bad implementations of Javascript would recalcuate the length property of the string every time you access it.

You can actually test this yourself using jsperf; using Chrome 12, it actually looks like your first example is faster.


In theory, I would expect that the second code block should be quicker.

However, given that today's JS interpreters are actually highly optimised JIT compilers, I would imagine that they would spot that kind of thing and optimise it.

That should apply to pretty much all browsers in current mainstream use, with the obvious exception of IE8 and lower, where it's anyone's guess how it does it, but it'll be slow either way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜