toArray vs slice

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var slice = Array.prototype.slice;
   
    function toArray(obj) {
      var arr = [];
      for (var i = 0, len = obj.length; i < len; i++) {
        arr[i] = obj[i];
      }
      return arr;
    }
   
    var test_arr1 = [];
    var test_arr2 = [];
    var test_arr3 = [];
   
    for (var i = 0; i < 10; i++) {
      test_arr1[i] = i;
    }
   
    for (var i = 0; i < 1000; i++) {
      test_arr2[i] = i;
    }
   
    for (var i = 0; i < 1000000; i++) {
      test_arr3[i] = i;
    }
};
</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
slice small
for (var i = 0; i < 100000; i++) {
  var temp = slice.call(test_arr1);
}
pending…
toArray small
for (var i = 0; i < 100000; i++) {
  var temp = toArray(test_arr1);
}
pending…
slice medium
for (var i = 0; i < 1000; i++) {
  var temp = slice.call(test_arr2);
}
pending…
toArray medium
for (var i = 0; i < 1000; i++) {
  var temp = toArray(test_arr2);
}
pending…
slice large
var temp = slice.call(test_arr3);
pending…
toArray large
var temp = toArray(test_arr3);
pending…
slice small single
var temp = slice.call(test_arr1);
pending…
toArray small single
var temp = toArray(test_arr1);
pending…
slice medium single
var temp = slice.call(test_arr2);
pending…
toArray medium single
var temp = toArray(test_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. Here’s a list of current revisions for this page:

0 comments

Add a comment