unaligned big endian read: dataview vs typed array views

JavaScript performance comparison

Revision 9 of this test case created by

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var nativeIsLittleEndian = new Uint16Array(new Uint8Array([0x12, 0x34]).buffer)[0] === 0x3412;
  
  var buf = new ArrayBuffer(1600);
  var uint8 = new Uint8Array(buf);
  var uint32 = new Uint32Array(buf);
  var view = new DataView(buf);
  
  for (var i = 0; i < 1600 / 4; ++i) {
    uint32[i] = i;
  }
  
  function readUInt32_1(position) {
    // assuming host is little endian. untested but mostly correct pbly :)
    var p = position >> 2;
    var o = position & 3;
    var a = uint32[p];
    var b = uint32[p + 1];
    if (o == 0) {
      return (((a & 0xFF) << 24) >>> 0) + ((a & 0xFF00) << 8) + ((a >> 8) & 0xFF00) + ((a >> 24) & 0xFF);
    } else if (o == 1) {
      return (((a & 0xFF00) << 16) >>> 0) + (a & 0xFF0000) + ((a >> 16) & 0xFF00) + (b & 0xFF);
    } else if (o == 2) {
      return (((a & 0xFF0000) << 8) >>> 0) + ((a & 0xFF000000) >> 8) + ((b & 0xFF) << 8) + ((b & 0xFF00) >> 8);
    } else {
      return ((a & 0xFF000000) >>> 0) + ((b & 0xFF) << 16) + ((b & 0xFF00) << 8) + ((b >> 16) & 0xFF);
    }
  }
  
  function readUInt32_2(position) {
    return view.getUint32(position);
  }
  
  function readUInt32_3(position) {
    var a0 = uint8[position],
      a1 = uint8[position + 1],
      a2 = uint8[position + 2],
      a3 = uint8[position + 3];
    return ((a0 << 24) >>> 0) + (a1 << 16) + (a2 << 8) + (a3);
  }
  
  function readUInt32_4(position) {
    return uint8[position + 3] +
      (uint8[position + 2] << 8) +
      (uint8[position + 1] << 16) +
      (uint8[position] * (1 << 24));
  }

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Typed Arrays
var x = 0;
for (var i = 0; i < 1600 - 3; i++) {
  x ^= readUInt32_1(i);
}
window.counter = x;
pending…
DataView
var x = 0;
for (var i = 0; i < 1600 - 3; i++) {
  x ^= readUInt32_2(i);
}
window.counter = x;
pending…
manual
var x = 0;
for (var i = 0; i < 1600 - 3; i++) {
  x ^= readUInt32_3(i);
}
window.counter = x;
pending…
manual alt
var x = 0;
for (var i = 0; i < 1600 - 3; i++) {
  x ^= readUInt32_4(i);
}
window.counter = x;
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.

0 Comments