3

I wanted to know what is computationally the fastest way to call a function nested in an object, so I made a quick jsPerf.com benchmark where I have considered three possibilities - calling a function from an array, from a 'core' object and from a function object:

var array = [1, 1, function(number) { return number; }];

var funcObj = function() {
    this.one = 1;
    this.two = 2;
    this.three = function(number) { return number; };
}
var someFunc = new funcObj();

var obj = {
    one: 1,
    two: 1,
    three: function(number) { return number; }
}

This is what happened:

And now, the question is: why there is so big difference?

EDIT: Link to the benchmark: >> link <<

6
  • >> link << Commented Jul 12, 2014 at 16:17
  • The numbers are the same in Firefox Commented Jul 12, 2014 at 16:27
  • 1
    Just for fun, you should try this under Firefox and Rhino. Commented Jul 12, 2014 at 16:33
  • Also, try the same thing with ~32, ~128, and ~1024 members rather than just 3. Commented Jul 12, 2014 at 16:36
  • 1
    Search for "v8 hidden classes". Commented Jul 12, 2014 at 17:07

1 Answer 1

5

Performance varies per implementation but here are some insights that might explain the difference:

First off, what you're measuring here is not the function call. You're measuring the lookup speed of array[2], someFunc.three and obj.three.

You see that arrays and objects are almost the same in speed but the new construction is significantly faster.

Array indexes and object properties can be resolved by binary search. I guess array indexes are slightly slower on the engine you tested.

A reason why the new construction might be so much faster is because it gets compiled into a class, which opens it up to a whole range of optimizations. I'm not sure if you gain performance because the lookup is faster or whether the optimization is elsewhere.


Another thing to note is that you shouldn't let yourself be guided by these small performance benchmarks. Under normal use either of those solutions is fine especially since they have an impact on how you write your code. If you have an actual performance problem it's much easier to make a good decision on where to optimize.

Sign up to request clarification or add additional context in comments.

1 Comment

As David Ehrmann properly pointed out - this is a browser-dependent issue, so f.e. on Firefox every lookup method is being performed with the same speed, so yeah, optimization is not being performed in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.