Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I speed up calls to native methods in JavaScript? [duplicate]

Tags:

javascript

According to this answer to 'Is object empty?':

// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;

I've seen several implementations of something similar in small JavaScript libraries, like:

var slice = Array.prototype.slice;

//or

function slice(collection) {
    return Array.prototype.slice.call(collection);
}

I did a quick jsperf to test this sort of thing, and caching looked a bit quicker overall than not caching, but my test could be flawed.

(I am using the word 'cache' to mean storing the method inside a variable.)

The context of this question is when a developer needs to call the native method multiple times, and what the observable difference would be.

Does caching the native method prevent the engine from having to look inside the object for the method every time the method is called, thus making caching a faster way to call native methods whenever the developer needs to call the same native method more than once?

like image 893
Josh Beam Avatar asked Feb 12 '14 22:02

Josh Beam


2 Answers

When you're using Array.prototype.slice a lot in, say, a library, it makes sense to create a variable holding that function (var slice = Array.prototype.slice;) because the variable can be minified by a JavaScript minifier which it can't otherwise.

Assigning the function to a variable also avoids having to traverse the object's prototype chain, which might result in a slightly better performance.

Note that this is micro-optimization, which you (generally speaking) shouldn't concern yourself too much with – leave that up to a modern JavaScript engine.

like image 135
Marius Schulz Avatar answered Nov 10 '22 19:11

Marius Schulz


Saving the value in a variable presents some optimization opportunities because if its a local variable the interpreter could do analyisis to realize that the vatiable never gets mutated. On the other hand, you always need to dereference globals like Array, since everyone could potentially change them at any time.

That said, I have no idea if this is going to matter for performance, expecially once you consider the JIT optimizations.

Usually, the biggest reason people use var slice is to keep the source code short.

like image 38
hugomg Avatar answered Nov 10 '22 19:11

hugomg