JavaScript 优化
所以我一直在用 JavaScript 编写游戏(不是网页游戏,使用游戏引擎,其中 JavaScript 恰好是脚本语言)。不幸的是,游戏引擎的JavaScript引擎是SpiderMonkey的古老版本,它运行我的游戏有点慢。虽然它不是很慢,但它已经足够慢了,所以我决定做一些优化。
我知道一些基本的优化,例如使用局部变量而不是全局变量(无论如何这是一个好主意),使用前缀而不是后缀增量/减量,在循环中倒数而不是向上计数,但是还有哪些更好的 JavaScript 优化呢?
So 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有尝试搞乱源代码,而是尝试了闭包编译器?它是一个从 javascript 到 javascript 的编译器,做了一些优化。大多数是为了大小,但生成的 js 运行速度通常也更快。但不知道优化是否特定于 V8。
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.
我不知道你的代码是如何构造的,但假设它的一部分驻留在经常运行的函数或循环中:
替换
如有可能,if()
吗? :例如
则将
if()
转换为switch()
substr()
、substring(),
或slice()
检查哪一个更快(在嵌入式浏览器上,我一旦注意到因子 3) 的差异。不过,请留意他们的参数!
eval() 非常慢(除了它是邪恶的事实),
如果代码难以阅读,请写注释。
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:
if()
with? :
where possiblee.g.
becomes
if()
s into aswitch()
if possiblesubstr()
,substring()
orslice()
check which one is faster (on an embedded browser Ionce noticed a difference of factor 3). Keep an eye on their parameters, though!
eval()
is very slow (besides the fact that it is evil)If the code turns out to be hard to read, write comments.