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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With