Maintaining a sorted array vs. push() and sort()

JavaScript performance comparison

Revision 8 of this test case created


The actual use-case isn't to sort for every insertion. Either you keep a sorted array, or you sort it at the end.

I removed linear search because it's so slow that freezes the browser.

Preparation code

function findBSearch(n, array) {
  var low = 0, high = array.length;
  while (low < high) {
    var mid = (low + high) >>> 1;
    array[mid] < n ? low = mid + 1 : high = mid;
  return low;
Benchmark.prototype.setup = function() {
    // Pseudo-random data.
    // I keep it the same for the sake of comparison.
    var input = [];
    for(i=0;i<30000;i++) input.push(Math.floor(Math.random()));

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
push() and sort()
var arr = [];
for (var i = 0, l = input.length; i < l; i++) {
arr.sort(function(a,b){return a-b;});
Binary search
var arr = [];
var pos;
for (var i = 0, l = input.length; i < l; i++) {
  pos = findBSearch(input[i], arr);
  arr.splice(pos, 0, input[i]);

Compare results of other browsers


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:

1 comment

Comment form temporarily disabled.

Add a comment