unaligned big endian read: dataview vs typed array views (v8)

Revision 8 of this benchmark created on


Setup

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 = uint32[position],
      a1 = uint32[position + 1],
      a2 = uint32[position + 2],
      a3 = uint32[position + 3];
    return ((a0 << 24) >>> 0) + (a1 << 16) + (a2 << 8) + (a3);
  }

Test runner

Ready to run.

Testing in
TestOps/sec
Typed Arrays
for (var i = 0; i < 1600 - 3; i++) {
  readUInt32_1(i);
}
ready
DataView
for (var i = 0; i < 1600 - 3; i++) {
  readUInt32_2(i);
}
ready
manual
for (var i = 0; i < 1600 - 3; i++) {
  readUInt32_3(i);
}
ready

Revisions

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