copy simple array

JavaScript performance comparison

Test case created by justageezer

Info

Quickest way to get a byval copy of an array of simple values - will NOT copy immutable objects in arrays byval e.g. nested arrays / objects etc get copied BYREF.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var a = [1, 2, 3, 4, 5, 6, 7, 8, 9],
        b = null;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
concat
b = a.concat();
pending…
slice w/index
b = a.slice(0);
pending…
slice w/o index
b = a.slice();
pending…
[]
b = [].concat(a);
pending…
new Array
b = new Array(a.join());
pending…
loop
var i = a.length,
    b = [];
for (;(i);) {
  --i;
  b.push(a[i]);
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

N commented :

Thanks, this was helpful for me to learn several alternatives (I wasn't aware of all of them), and their relative performance.

Elliot Geno commented :

Did you mean to push the item into the array? It would result in a reversed array.

Add a comment