Skip to content

Large Collection Copy (ARCH3086)

Key typescript.performance.large-collection-copy · Severity info · Category performance

Dumping an entire collection into an array or spread-copying it when only a few elements are needed allocates needless memory; streaming or slicing should be preferred.

function firstThree<T>(source: Iterable<T>): T[] {
return [...source].slice(0, 3);
}
function firstThree<T>(source: Iterable<T>): T[] {
const result: T[] = [];
for (const item of source) {
result.push(item);
if (result.length === 3) break;
}
return result;
}

Iterate the stream and take only the elements you need instead of materializing the whole collection.