Skip to content

Commit 61b0190

Browse files
committed
Optimize findOverlap.
In most cases, append() appends something to the last of the existing ranges, so we iterate ranges in the reverse order. This matters if the ranges are heavily fragmentated.
1 parent cd49e3d commit 61b0190

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

multi-integer-range.ts

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -151,28 +151,26 @@ export class MultiRange {
151151
//
152152
// findOverlap(C) returns { lo: 3, count: 0, union: <i-k> }
153153
// meaning (C) is between (2) and (3) but overlaps/touches neither of them.
154-
//
155154

156-
let lim = this.ranges.length;
157-
for (let lo = 0; lo < lim; lo++) {
158-
let r = this.ranges[lo];
155+
for (let hi = this.ranges.length - 1; hi >= 0; hi--) {
156+
let r = this.ranges[hi];
159157
let union;
160158
if (union = this.calcUnion(r, target)) {
161159
let count = 1;
162160
let tmp;
163-
while ((lo + count < lim) && (tmp = this.calcUnion(union, this.ranges[lo+count]))) {
161+
while ((hi - count >= 0) && (tmp = this.calcUnion(union, this.ranges[hi - count]))) {
164162
union = tmp;
165163
count++;
166164
}
167165
// The given target touches or overlaps one or more of the existing ranges
168-
return { lo, count, union };
169-
} else if (r[0] > target[1] + 1) {
166+
return { lo: hi + 1 - count, count, union };
167+
} else if (r[1] < target[0]) {
170168
// The given target does not touch nor overlap the existing ranges
171-
return { lo, count: 0, union: target }
169+
return { lo: hi + 1, count: 0, union: target };
172170
}
173171
}
174-
// The given target is larger than the largest existing range
175-
return { lo: lim, count: 0, union: target };
172+
// The given target is smaller than the smallest existing range
173+
return { lo: 0, count: 0, union: target };
176174
}
177175

178176

0 commit comments

Comments
 (0)