Typed Arrays vs Arrays

JavaScript performance comparison

Test case created by Ben Vanik

Info

Checking the performance of Typed Arrays vs. JS arrays for image processing-like work.

Preparation code

<script>
  function fillArray(a) {
   var n = 0;
   for (var y = 0; y < 1024; y++) {
    for (var x = 0; x < 1024; x++) {
     a[n++] = x % 128 + 1;
     a[n++] = x % 128 + 2;
     a[n++] = x % 128 + 3;
     a[n++] = x % 128 + 4;
    }
   }
  };
 
  function fillArray32(a) {
   var n = 0;
   for (var y = 0; y < 1024; y++) {
    for (var x = 0; x < 1024; x++) {
     var a = x % 128 + 1;
     var r = x % 128 + 2;
     var g = x % 128 + 3;
     var b = x % 128 + 4;
     a[n++] = (a << 24) | (r << 16) | (g << 8) | b;
    }
   }
  };
 
  function multiplyArray(a, s) {
   var n = 0;
   for (var y = 0; y < 1024; y++) {
    for (var x = 0; x < 1024; x++) {
     a[n++] *= s;
     a[n++] *= s;
     a[n++] *= s;
     a[n++] *= s;
    }
   }
  };
 
  function multiplyArray32(a, s) {
   var n = 0;
   for (var y = 0; y < 1024; y++) {
    for (var x = 0; x < 1024; x++) {
     var v = a[n];
     var a = (v >> 24) & 0xFF;
     var r = (v >> 16) & 0xFF;
     var g = (v >> 8) & 0xFF;
     var b = (v) & 0xFF;
     a *= s;
     r *= s;
     g *= s;
     b *= s;
     a[n++] = (a << 24) | (r << 16) | (g << 8) | b;
    }
   }
  };
 
  var s_jsarray = [];
  s_jsarray.length = 1024 * 1024 * 4;
  for (var n = 0; n < s_jsarray.length; n++) {
   s_jsarray[n] = 0;
  }
  var s_tyarray8 = new Uint8Array(1024 * 1024 * 4);
  var s_tyarray32 = new Uint32Array(1024 * 1024);
 
  var canvas = document.createElement("canvas");
  document.body.appendChild(canvas);
  var ctx = canvas.getContext("2d");
  var s_caarray = ctx.createImageData(1024, 1024).data;
</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
JS Create
var jsarray = [];
jsarray.length = 1024 * 1024 * 4;
for (var n = 0; n < jsarray.length; n++) {
 jsarray[n] = 0;
}
pending…
Typed Create (byte)
var tyarray = new Uint8Array(1024 * 1024 * 4);
pending…
Typed Create (uint)
var tyarray = new Uint32Array(1024 * 1024);
pending…
JS Fill
fillArray(s_jsarray);
pending…
Typed Fill (byte)
fillArray(s_tyarray8);
pending…
Typed Fill (uint)
fillArray32(s_tyarray32);
pending…
JS Multiply
multiplyArray(s_jsarray, 1);
pending…
Typed Multiply (byte)
multiplyArray(s_tyarray8, 1);
pending…
Typed Multiply (uint)
multiplyArray32(s_tyarray32, 1);
pending…
Canvas Create
var caarray = ctx.createImageData(1024, 1024).data;
pending…
Canvas Fill
fillArray(s_caarray);
pending…
Canvas Multiply
multiplyArray(s_caarray, 1);
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