1

What is the difference between [].slice vs Array.prototype.slice?

While searching, I found Array.prototype.slice to be faster than [].slice at jsperf.com/array-prototype-slice-vs-slice.

Why Array.prototype.slice is faster than [].slice?

I have checked [].slice or Array.prototype.slice. A more vivid description will be helpful.

Thanks

1

2 Answers 2

4

Why Array.prototype.slice is faster than [].slice?

[] is an instance of Array, so the additional overhead is most likely the time it takes to instantiate the object.

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

2 Comments

Thanks, I guessed so but got confused by stackoverflow.com/questions/9006553/… and then seeing the performance impact at jsperf.com/array-prototype-slice-vs-slice +1
There's a bit more to it than that! See stackoverflow.com/a/52820058/2427596
4

.slice() is an Array prototype method. It is defined on the Array prototype object, Array.prototype, which means that Array.prototype.slice is the direct way to reference it.

Array instances, like [], inherit from the Array prototype, so [].slice resolves to Array.prototype.slice.

If you need to use this method repeatedly, a good approach is to put its reference into a variable in your outermost scope:

var slice = Array.prototype.slice;

and then use this variable via .call() and .apply() calls, e.g.

slice.call( someObj )

1 Comment

Thanks for clarifying the difference, I was mainly looking for the reason behind performance impact. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.