Can I speed up calls to native methods in JavaScript?
javascript
Solution
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.
Problem
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?