Search code examples
javascriptperformancestructarraybuffer

How to read a struct from a JS ArrayBuffer efficiently (browser)?


Let's say I have a struct of the form

typedef struct {
  uint32_t intensity;
  uint16_t ring;
  float32_t x;
  float32_t y;
  float32_t z;
} Point;

(18 bytes total) and I have a huge array of several tens of thousands of these 18-byte structs in an ArrayBuffer.

How do I iterate through them efficiently without calling a "new DataView()" constructor irritatively in a loop?

This is in the browser, not NodeJS.


Solution

  • There's no need to create a new DataView each time you read a value. Create it just once and use offset to read data at the specific location:

    let dv = new DataView(buffer);
    let offset = 0;
    
    while (offset < buffer.byteLength) {
        intensity = dv.getUint32(offset);  offset += 32;
        ring = dv.getUint16(offset);       offset += 16;
        // etc
    }
    

    }