unshift vs push.apply vs concat

Benchmark created by James on


Description

What is most efficient when we wish to join a small beginning array with a large array in that order?

For example, I wish to concatenate [1,2,3] with [4,5,6...10000]. Is it quicker to unshift the small array onto the large one, concat them together, or push.apply the contents of the large one onto the small one?

I don't care what happens to the initial arrays, I just need a reference to the joined result.

Setup

var first = [1,2,3,4,5,6,7,8,9,10]
    var second = [];
    for(var i = 10; i < 10000; i++) second.push(i);

Test runner

Ready to run.

Testing in
TestOps/sec
unshifting first array onto second
second.unshift.apply(second, first);
ready
concatenating first and second
first.concat(second)
ready
pushing contents of second array onto first
first.push.apply(first, second);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by James on