flatten

JavaScript performance comparison

Test case created by Josh

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function flatpop1(arr) {
      var flat = [];
      while (arr.length) {
        var last = arr.pop();
        if (Array.isArray(last)) {
          Array.prototype.push.apply(arr, last);
        } else {
          flat.push(last);
        }
      }
      return flat.reverse();
    }
   
    function flatpop2(arr) {
      arr = arr.slice();
      var flat = [];
      while (arr.length) {
        var last = arr.pop();
        if (Array.isArray(last)) {
          Array.prototype.push.apply(arr, last);
        } else {
          flat.push(last);
        }
      }
      return flat.reverse();
    }
   
    var walk = function(out, arr) {
      for (var i = 0; i < arr.length; i++) {
          if (!Array.isArray(arr[i])) {
            out.push(arr[i]);
          } else {
            walk(out, arr[i]);
          }
      }
    }
   
    function flatrecur(arr) {
      var out = [];
      walk(out, arr);
      return out;
    }
};
</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
pop1
flatpop1([1, 2, [3, 4, [5, 6], 7, 8], 9]);
pending…
pop2
flatpop2([1, 2, [3, 4, [5, 6], 7, 8], 9]);
pending…
recur
flatrecur([1, 2, [3, 4, [5, 6], 7, 8], 9]);
pending…

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

Compare results of other browsers

0 comments

Add a comment