Optimizing performance of _BinaryWriter._resizeBuffer

In class _BinaryWriter of the gltf exporter, a loop is used to copy contents in old buffer to new buffer, which is benchmarked to be slow.

TypedArray.prototype.set() can be used for faster memory copying while having the same Browser compatibility of TypedArray.

Proposed code:

BABYLON.GLTF2.Exporter._BinaryWriter.prototype._resizeBuffer = function _resizeBuffer(byteLength) {
    const newBuffer = new ArrayBuffer(byteLength);
    let oldUint8Array = new Uint8Array(this._arrayBuffer);
    const newUint8Array = new Uint8Array(newBuffer);
    if (oldUint8Array.length > newUint8Array.length) {
        oldUint8Array = oldUint8Array.subarray(0, newUint8Array.length);
    newUint8Array.set(oldUint8Array, 0);
    this._arrayBuffer = newBuffer;
    this._dataView = new DataView(this._arrayBuffer);

    return newBuffer;

Benchmark before:

Benchmark after:

The model used for benchmarking:
Arm.zip (3.0 MB)
source of this model

1 Like

This might interest @bghgary

I like it !!!

1 Like

Yes, this would be a good change! Please submit a PR. :slight_smile:

1 Like
1 Like