Typed Arrays

Generated fixture that type-checks typed-array constructor and from() overload surfaces.

tsz is 5.4x faster 53 lines 2 KB

Timing

tsz
68.04ms
tsgo
370.37ms

Files

// Typed array benchmark fixture used by bench-vs-tsgo.sh.
// Keep this strict/explicit so all compilers can parse and type-check it.

function createTypedArrayInstancesFromLength(length: number) {
    const typedArrays = [];
    typedArrays[0] = new Int8Array(length);
    typedArrays[1] = new Uint8Array(length);
    typedArrays[2] = new Int16Array(length);
    typedArrays[3] = new Uint16Array(length);
    typedArrays[4] = new Int32Array(length);
    typedArrays[5] = new Uint32Array(length);
    typedArrays[6] = new Float32Array(length);
    typedArrays[7] = new Float64Array(length);
    typedArrays[8] = new Uint8ClampedArray(length);
    return typedArrays;
}

function createTypedArrayInstancesFromArrayLike(obj: ArrayLike<number>) {
    const typedArrays = [];
    typedArrays[0] = new Int8Array(obj);
    typedArrays[1] = new Uint8Array(obj);
    typedArrays[2] = new Int16Array(obj);
    typedArrays[3] = new Uint16Array(obj);
    typedArrays[4] = new Int32Array(obj);
    typedArrays[5] = new Uint32Array(obj);
    typedArrays[6] = new Float32Array(obj);
    typedArrays[7] = new Float64Array(obj);
    typedArrays[8] = new Uint8ClampedArray(obj);
    return typedArrays;
}

function createTypedArraysFromMapFn(
    obj: ArrayLike<number>,
    mapFn: (n: number, v: number) => number
) {
    const typedArrays = [];
    typedArrays[0] = Int8Array.from(obj, mapFn);
    typedArrays[1] = Uint8Array.from(obj, mapFn);
    typedArrays[2] = Int16Array.from(obj, mapFn);
    typedArrays[3] = Uint16Array.from(obj, mapFn);
    typedArrays[4] = Int32Array.from(obj, mapFn);
    typedArrays[5] = Uint32Array.from(obj, mapFn);
    typedArrays[6] = Float32Array.from(obj, mapFn);
    typedArrays[7] = Float64Array.from(obj, mapFn);
    typedArrays[8] = Uint8ClampedArray.from(obj, mapFn);
    return typedArrays;
}

const values: number[] = [1, 2, 3, 4];
const mapped = createTypedArraysFromMapFn(values, (n, i) => n + i);
const fromLength = createTypedArrayInstancesFromLength(128);
const fromArrayLike = createTypedArrayInstancesFromArrayLike(values);
const sampleCount = mapped.length + fromLength.length + fromArrayLike.length;