DataView float

Benchmark created by m-schuetz on


Preparation HTML

<p>
DataView offers a standard and easy to use API to read float and integer values of various sizes from a binary buffer at arbitrary byte offsets.

Unfortunately, Firefox's DataView implementation seems to be two orders of magnitudes slower than that of Chrome. Reading 3D models from binary files or processing/transforming 3D data in binary buffers frequently requires the use of DataView. A widely used hack is to use a 4 byte Uint8Array buffer instead, copy the relevant 4 bytes from the source buffer into it, and then interpret this Uint8Array as a Float32Array to retrieve the value. While this is faster than DataView in Firefox, it is also considerably sloer than DataView in chrome. It is also a rather unfortunate and ugly hack.
</p>

Setup

function createTestData(size){
  
  	let buffer = new ArrayBuffer(4 * size);
  	let f32 = new Float32Array(buffer);
  
  	for(let i = 0; i < size; i++){
  		f32[i] = Math.random();
  	}
  
  	return buffer;
  }
  
  let n = 1_000_000;
  let buffer = createTestData(n);

Test runner

Ready to run.

Testing in
TestOps/sec
using DataView
let view = new DataView(buffer);

let sum = 0;
for(let i = 0; i < n; i++){
	let value = view.getFloat32(4 * i, true);
	sum += value;
}
let mean = sum / n;

console.log(`mean: ${mean}`);
ready
using u8 array hack
let view = new Uint8Array(buffer);

let hackBuffer = new ArrayBuffer(4);
let hackU8 = new Uint8Array(hackBuffer);
let hackF32 = new Float32Array(hackBuffer);

let sum = 0;
for(let i = 0; i < n; i++){
	hackU8[0] = view[4 * i + 0];
	hackU8[1] = view[4 * i + 1];
	hackU8[2] = view[4 * i + 2];
	hackU8[3] = view[4 * i + 3];

	let value = hackF32[0];
	sum += value;
}
let mean = sum / n;

console.log(`mean: ${mean}`);
ready

Revisions

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

  • Revision 1: published by m-schuetz on