dataview vs typed array views (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script>
var source = new Uint8Array([0x32, 0x65, 0x42, 0x56]);
var nativeEndian = new Uint16Array(new Uint8Array([0x12, 0x34]).buffer)[0] === 0x3412;

var buf = new ArrayBuffer(16);
var uint8 = new Uint8Array(buf);
var int8 = new Int8Array(buf);
var uint16 = new Uint16Array(buf);
var int16 = new Int16Array(buf);
var uint32 = new Uint32Array(buf);
var int32 = new Int32Array(buf);
var float32 = new Float32Array(buf);
var float64 = new Float64Array(buf);

function peek(bytes, littleEndian) {
    var i, _i, _j;
    if (littleEndian == null) {
      littleEndian = false;
    }
    if (littleEndian === nativeEndian) {
      for (i = _i = 0; _i < bytes; i = _i += 1) {
        uint8[i] = source[i];
      }
    } else {
      for (i = _j = 0; _j < bytes; i = _j += 1) {
        uint8[bytes - i - 1] = source[i];
      }
    }
  }

function readUInt32_1(littleEndian) {
  peek(4, littleEndian);
  return uint32[0];
}

var buf2 = new ArrayBuffer(10);
var uint8_2 = new Uint8Array(buf2);
var view = new DataView(buf2);

function peek2(bytes) {
  for (var i = 0; i < bytes; i++) {
    uint8_2[i] = source[i];
  }
}

function readUInt32_2(littleEndian) {
  peek2(4);
  return view.getUint32(0, littleEndian);
}

function readUInt32_3(littleEndian) {
  var a0 = source[0],
      a1 = source[1],
      a2 = source[2],
      a3 = source[3];
  
  if (littleEndian)
    return ((a3 << 24) >>> 0) + (a2 << 16) + (a1 << 8) + (a0);
  else
    return ((a0 << 24) >>> 0) + (a1 << 16) + (a2 << 8) + (a3);
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Typed Arrays
readUInt32_1();
ready
DataView
readUInt32_2();
ready
Bit twiddling
readUInt32_3();
ready

Revisions

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