Skip to content

Commit 644d655

Browse files
committed
Optimize core filter function to only allocate when necessary
1 parent 29ae2b2 commit 644d655

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

src/compiler/core.ts

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -147,17 +147,29 @@ namespace ts {
147147
return count;
148148
}
149149

150+
/**
151+
* Filters an array by a predicate function. Returns the same array instance if the predicate is
152+
* true for all elements, otherwise returns a new array instance containing the filtered subset.
153+
*/
150154
export function filter<T>(array: T[], f: (x: T) => boolean): T[] {
151-
let result: T[];
152155
if (array) {
153-
result = [];
154-
for (const item of array) {
155-
if (f(item)) {
156-
result.push(item);
156+
const len = array.length;
157+
let i = 0;
158+
while (i < len && f(array[i])) i++;
159+
if (i < len) {
160+
const result = array.slice(0, i);
161+
i++;
162+
while (i < len) {
163+
const item = array[i];
164+
if (f(item)) {
165+
result.push(item);
166+
}
167+
i++;
157168
}
169+
return result;
158170
}
159171
}
160-
return result;
172+
return array;
161173
}
162174

163175
export function filterMutate<T>(array: T[], f: (x: T) => boolean): void {

0 commit comments

Comments
 (0)