Why does calling a function without its owner is slower?

349 views Asked by At

If I do the following:

var abs = Math.abs;

Shoudn't abs(-10) be faster than Math.abs(-10)? Because abs is called directly.

This is what called my attention: Math.abs vs custom abs function Result of a test done at jsperf.com

Update:

The same test performed in the Internet Explorer 11 shows a completely different result: Result of a test done at jsperf.com

I'd speculate that this is due to some optimizations on built-in functions in Chrome's V8 Engine.

A test created by nnnnnn that clarifies what I am trying to say: Property shortcut Result of a test done at jsperf.com

1

There are 1 answers

5
Teodor Sandu On

This answer was rendered useless by Givi. See comments.

Looking up a user-defined function in a user-defined object is slower than looking up a function bound to a local variable, so you were mostly right.

However, looking up Math.* functions is faster, most probably because of internal optimizations of the V8 engine (so "caching" built-in functions in a local variable is actually slower, while "caching" user-defined functions is faster).

Edit: here's a jsperf demonstrating how Math.* functions are faster than their var x = Math.x counterparts, while doing the same for user defined function is not. It's just how V8 works imho. test results

Edit #2: just now i noticed this line from your question:

I'd speculate that this is due to some optimizations on built-in functions in Chrome's V8 Engine.

I'm not 100% sure, but it definitely looks that way, yes.