splice(0): the fastest way to copy a JS array
Edit: Actually, this modifies the original. Not a true copy. See comments.
No matter what the contents of the array (int, float, string, object, array, mixed), the fastest way to copy the array (by FAR) is:
var copied = original.splice(0);
Here's the JS perf: http://jsperf.com/array-copy-techniques
Written by Jasper Palfree
Related protips
3 Responses
it's more like "move" rather than "copy" :(
over 1 year ago
·
I agree with @zhuangya . This is a volatile copy and should be avoided.
var a = [1, 2, 3],
b = a.splice(0);
console.log(a); // [] - empty array since all members have been transferred to b
console.log(b); // [1, 2, 3] - transferred members of a
over 1 year ago
·
@twolfson Totally correct. Thanks for the correction.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Optimization
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#