JavaScript optimization: Caching math functions globally
I'm currently doing some "extreme" optimization on a JavaScript game engine I'm writing. And I have noticed I use math functions a lot! And I'm currently only caching them locally per function I use them in. So I was going to cache them at the global level in the window object using the below code.
var aMathFunctions = Object.getOwnPropertyNames(Math);
for (var i in aMathFunctions)
{
window[aMathFunctions[i]] = Math[aMathFunctions[i]];
}
Are there any major problems or side effects with this? Will I be overwriting existing functions in window, and will I be increasing my memory footprint dramatically? Or what else may go wrong?
EDIT: Below is an excerpt on reading I have done about JavaScript optimization that has lead me to try this.
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 name开发者_如何转开发spacing 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.
Reference: http://www.phpied.com/extreme-javascript-optimization/
Edit: Should not matter anymore in Chrome due to this revision; perhaps caching is now even faster.
Don't do it, it's much slower when using global functions.
http://jsperf.com/math-vs-global
On Chrome:
sqrt(2); - 12,453,198 ops/second
Math.sqrt(2); - 542,475,219 ops/second
As for memory usage, globalizing it wouldn't be bad at all on the other hand. You just create another reference; the function itself will not be copied.
I am actually amazed it is faster for me on Mac OS X and Firefox 5 talking 5-8 ms difference in 50000 iterations.
console.time("a");
for (var i=0;i<50000;i++) {
var x = Math.floor(12.56789);
}
console.timeEnd("a");
var floor = Math.floor;
console.time("b");
for (var i=0;i<50000;i++) {
var y = floor(12.56789);
}
console.timeEnd("b");
I see only one real bonus if it will reduce the footprint of the code. I have not tested any other browsers so it may be a boost in one and slower in others.
Would it cause any problems? I don't see why it would unless you have things in global scope with those names. :)
精彩评论