JavaScript 优化

发布于 2024-10-09 11:29:37 字数 251 浏览 1 评论 0原文

所以我一直在用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安人多梦 2024-10-16 11:29:37

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.

一页 2024-10-16 11:29:37

我不知道你的代码是如何构造的,但假设它的一部分驻留在经常运行的函数或循环中:

  • 替换 if() 吗? : 如有可能,

例如

if (expr) a = 1;
else a = 2;

则将

a = expr ? 1 : 2;
  • 一系列 if() 转换为 switch()
  • 如果可能的话,如果您使用 substr()substring(),slice() 检查哪一个更快(在嵌入式浏览器上,我
    一旦注意到因子 3) 的差异。不过,请留意他们的参数!
  • 避免重新计算值或再次使用相同的参数调用相同的函数,即使只是一个小函数,
  • 如果您一遍又一遍地访问数组的相同元素,请将其存储在局部变量
  • eval() 非常慢(除了它是邪恶的事实),
  • 请记住 JavaScript 引擎是单线程的。没有什么是并行运行的,甚至计时器或间隔也是如此。

如果代码难以阅读,请写注释。

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 a switch() if possible
  • if you use substr(), substring() or slice() 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文