Quick JS experiment: Function Overhead

Probably common knowledge, but I just slapped together a quick test script to determine what kind of overhead there is between a) writing a function inline, b) keeping the function as part of an object (say, utility.isObject), and c) same as b, but get a reference to the function first. Each approach was iterated a total of 100,000,000 times to get usable time values. Tests were performed in Chrome 7, so YMMV.

Results:

A: typeof obj == “object” : 439 msec
B: util.isObj(obj) : 1228 msec (where util = { isObj : function(o) { return typeof o == “object”; } })
C: isObj(obj) : 1155 msec (where B and isObj = util.isObj)

Conclusions:

First, remember that these are looping over 100 million iterations. This kind of research might be useful for a worker thread, but it’s not terribly useful for day to day stuff.

The big conclusion here is if you’re only going to call a function from one or two places, or it’s very short, skipping the function and putting the code inline will save you about 60%, but it’s really only significant if you’re calling that function millions of times.

The second conclusion is that if you must use a function for something like this (millions of calls), you can save a tiny bit—almost completely insignificant—of time by getting a reference to that function. Keep in mind that this micro-optimization only works if the function you’re calling doesn’t require context. If you have to use the .call or .apply methods to add context, this approach is actually about 17x slower.

Actual testing code at http://jsfiddle.net/jsylvanus/tTsXp/

Tags: , , ,

Leave a Reply