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
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.
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:
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.