merge-array implementations

JavaScript performance comparison

Revision 37 of this test case created by Dennis Cheung

Preparation code

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
      
<script>
Benchmark.prototype.setup = function() {
  var arr1 = Array.from(Array(50000), (x,i) => i + 1)
  var arr2 = Array.from(Array(50000), (x,i) => i - 1)
  
  var arr1Length = arr1.length; 
  var arr2Length = arr2.length; 

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Just Copy naive
var arr1a=new Array(arr1Length), arr2a=new Array(arr2Length);
for(var i = 0; i < arr1Length; i++){
  arr1a[i] = arr1[i]
}
for(var i = 0; i < arr2Length; i++){
  arr2a[i] = arr2[i]
}
pending…
unshift
Array.prototype.unshift.apply(arr2,arr1);
pending…
push (naive 1)
for(var i = 0; i < arr2Length; i++){
  arr1[arr1Length + i] = arr2[i]
}
pending…
push (naive 3)
for(var i = 0; i < arr2Length; i++){
  arr1.push(arr2[i])
}
pending…
concat
var arr3 = arr1.concat(arr2)
pending…
splice
arr1.length+=arr2Length;
Array.prototype.splice.bind(arr1, arr1Length, arr2Length).apply(arr1, arr2);
pending…
flatMap
[arr1,arr2].flatMap(Object)
pending…
concat (naive 1)
// Create result array
var arr3 = []

// Add Array 1
for(var i = 0; i < arr1Length; i++){
  arr3[i] = arr1[i]
}

// Add Array 2
for(var i = 0; i < arr2Length; i++){
  arr3[arr1Length + i] = arr2[i]
}
pending…
concat (naive 2)
// Create result array with preallocated size
var arr3 = Array(arr1Length + arr2Length)

// Add Array 1
for(var i = 0; i < arr1Length; i++){
  arr3[i] = arr1[i]
}

// Add Array 2
for(var i = 0; i < arr2Length; i++){
  arr3[arr1Length + i] = arr2[i]
}
pending…
push (naive 2)
// Pre allocate size
arr1.length = arr1Length + arr2Length

// Add arr2 items to arr1
for(var i = 0; i < arr2Length; i++){
  arr1[arr1Length + i] = arr2[i]
}
pending…
push
Array.prototype.push.apply(arr1, arr2)
pending…
concat (naive 3)
var arr3 = Array.from(arr1);
for(var i = 0; i < arr2Length; i++){
  arr3[arr1Length + i] = arr2[i]
}
pending…
Just Array.from
var arr1a = Array.from(arr1);
var arr2a = Array.from(arr2);
pending…
concat by push
var arr3=Array.of(arr1);
Array.prototype.push.apply(arr3, arr2);
pending…
_.concat
arr1 = _.concat(arr1, arr2)
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.

0 Comments