typescript / intermediate
Snippet
Optimizing Heavy Operations with Readonly Array Buffers
Using `readonly number[]` types alongside `Object.freeze()` prevents accidental mutations during array traversals, enabling compiler optimizations and safeguarding shared memory structures in performance-critical code.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
function computeTotals(numbers: readonly number[]): number {let sum = 0;for (let i = 0; i < numbers.length; i++) {sum += numbers[i];}return sum;}const dataSet: readonly number[] = Object.freeze([10, 20, 30, 40]);const total = computeTotals(dataSet);console.log("Total:", total);
Breakdown
1
function computeTotals(numbers: readonly number[]): number
Ensures the parameter input array cannot be mutated inside the function scope.
2
const dataSet: readonly number[] = Object.freeze([10, 20, 30, 40]);
Freezes the array at runtime and matches the readonly type signature at compile time.