gpt4 book ai didi

JavaScript优化: Caching math functions globally

转载 作者:行者123 更新时间:2023-12-03 06:44:48 24 4
gpt4 key购买 nike

我目前正在对我正在编写的 JavaScript 游戏引擎进行一些“极端”优化。我注意到我经常使用数学函数!目前,我仅在每个使用它们的函数中本地缓存它们。因此,我将使用以下代码在窗口对象中的全局级别缓存它们。

var aMathFunctions = Object.getOwnPropertyNames(Math);

for (var i in aMathFunctions)
{
window[aMathFunctions[i]] = Math[aMathFunctions[i]];
}

这有什么重大问题或副作用吗?我是否会覆盖窗口中的现有函数,是否会显着增加内存占用?或者还有什么可能出错的地方?

编辑:下面是我阅读过的关于 JavaScript 优化的摘录,这促使我尝试了这个。

Property Depth

Nesting objects in order to use dot notation is a great way to namespace and organize your code. Unforutnately, when it comes to performance, this can be a bit of a problem. Every time a value is accessed in this sort of scenario, the interpreter has to traverse the objects you've nested in order to get to that value. The deeper the value, the more traversal, the longer the wait. So even though namespacing is a great organizational tool, keeping things as shallow as possible is your best bet at faster performance. The latest incarnation of the YUI Library evolved to eliminate a whole layer of nesting from its namespacing. So for example, YAHOO.util.Anim is now Y.Anim.

引用:http://www.phpied.com/extreme-javascript-optimization/

最佳答案

编辑: 在 Chrome 中应该不再重要了,因为 this revision ;也许缓存现在更快。

<小时/>

不要这样做,使用全局函数会慢得多。

http://jsperf.com/math-vs-global

在 Chrome 上:

sqrt(2);      - 12,453,198  ops/second
Math.sqrt(2); - 542,475,219 ops/second

至于内存使用,另一方面,全局化也不会太糟糕。您只需创建另一个引用;函数本身不会被复制。

关于JavaScript优化: Caching math functions globally,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7056838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com