views:

35

answers:

1

I was looking at some code and have seen these comments, how does promoting a function to global help performance?

// this function is promoted to be global
// to make firefoxs jit happy - URGH

function clamp(x, min, max) {
if(x < min) return min;
if(x > max) return max-1;
return x;
}
+2  A: 

Because functions are instantiated only when they come into scope. If the function were defined within another function, it would be instantiated every time that outer function was called. Making it global ensures that it is instantiated only once.

Whether this is going to have a visible impact on performance depends on the actual program flow. If at all, such optimizations are useful only, for example, if clamp were to be defined inside another function and that function is repeatedly called a large number of times within a loop.

casablanca