2

This is related to: How do I pass the value instead of the refererence of an array?

I need to send the value instead of reference to an array. To that question I got 2-3 valid answers. One was use slice, second (and third was similar) was to use clone or make my own clone function.

From a (very) quick test, it seems like slice was faster (tested on a 100,000 elements array). But I don't have any explanation for that.

Can anyone clarify if and why is slice faster?

Community
  • 1
  • 1
zozo
  • 8,230
  • 19
  • 79
  • 134

1 Answers1

5

The clone function presented in that answer is very general (also quite poor; never, ever, ever add enumerable properties to Object.prototype, and there are other issues as well), and is implemented in JavaScript. In contrast, the slice answer uses the JavaScript engine's built-in function, which can be written in highly optimized machine code. (Or not, of course.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875