JavaScript optimizations
S开发者_JS百科o I've been writing a game in JavaScript (not a web game, using a game engine where JavaScript just happens to be the scripting language). Unfortunately, the game engine's JavaScript engine is an ancient version of SpiderMonkey, which runs my game a bit slowly. While it's not terribly slow, it's slow enough that I decided to do a bit of optimization.
I know some basic optimizations like using local variables instead of globals (which is a good idea anyway), using prefix instead of postfix increment/decrement, counting down instead of up in loops, but what are some more good JavaScript optimizations?
Instead of messing up the source code did you give a try to the Closure Compiler ? It's a compiler from javascript to javascript that does a few optimizations. Mostly are for size but the resulting js also runs often faster. No idea if optimizations are however V8-specific.
I don't know how your code is structured, but let's say that parts of it reside in functions or loops, which are run through frequently:
- replace
if()
with? :
where possible
e.g.
if (expr) a = 1;
else a = 2;
becomes
a = expr ? 1 : 2;
- turn a series of
if()
s into aswitch()
if possible - if you use
substr()
,substring()
orslice()
check which one is faster (on an embedded browser I once noticed a difference of factor 3). Keep an eye on their parameters, though! - avoid recalculation of values or calling the same function with the same parameters again, even if it's just a minor one
- if you access the same element of an array over and over again, store it in a local variable
eval()
is very slow (besides the fact that it is evil)- keep in mind that a JavaScript-engine is single-threaded. Nothing runs parallel, not even timers or intervals.
If the code turns out to be hard to read, write comments.
精彩评论