Minimize object creation and memory copying operations to improve performance. Cache and reuse objects when possible, use buffer views instead of copying data, and avoid creating temporary objects that will be immediately discarded.
Key practices:
new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength)
) instead of copying data twiceBuffer.concat()
instead of manual array operationsExample of inefficient allocation:
// Creates unnecessary ReadableStream that gets overwritten
let stream = this.bindingsResponse.body || new ReadableStream();
if (options?.encoding === 'base64') {
stream = stream.pipeThrough(createBase64EncoderTransformStream());
}
// Creates new Reader on every call
const reader = this._stream.getReader();
Example of optimized allocation:
// Only create ReadableStream when needed
const stream = options?.encoding === 'base64'
? (this.bindingsResponse.body || new ReadableStream()).pipeThrough(createBase64EncoderTransformStream())
: (this.bindingsResponse.body || new ReadableStream());
// Cache and reuse Reader
if (!this._cachedReader) {
this._cachedReader = this._stream.getReader();
}
Enter the URL of a public GitHub repository