Skip to content

Commit 7501fe6

Browse files
committed
Improve performance of shared/utils.js::intersect
- avoid to call normalizeRect which clones the rectangles: it's useless and time consuming; - in profiling the pdf in bug 1135277, the time spent in intersect drops from ~1s to ~30ms.
1 parent 143ba30 commit 7501fe6

File tree

1 file changed

+20
-33
lines changed

1 file changed

+20
-33
lines changed

src/shared/util.js

+20-33
Original file line numberDiff line numberDiff line change
@@ -827,46 +827,33 @@ class Util {
827827
}
828828

829829
// Returns a rectangle [x1, y1, x2, y2] corresponding to the
830-
// intersection of rect1 and rect2. If no intersection, returns 'false'
830+
// intersection of rect1 and rect2. If no intersection, returns 'null'
831831
// The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2]
832832
static intersect(rect1, rect2) {
833-
function compare(a, b) {
834-
return a - b;
835-
}
836-
837-
// Order points along the axes
838-
const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
839-
const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
840-
const result = [];
841-
842-
rect1 = Util.normalizeRect(rect1);
843-
rect2 = Util.normalizeRect(rect2);
844-
845-
// X: first and second points belong to different rectangles?
846-
if (
847-
(orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) ||
848-
(orderedX[0] === rect2[0] && orderedX[1] === rect1[0])
849-
) {
850-
// Intersection must be between second and third points
851-
result[0] = orderedX[1];
852-
result[2] = orderedX[2];
853-
} else {
833+
const xLow = Math.max(
834+
Math.min(rect1[0], rect1[2]),
835+
Math.min(rect2[0], rect2[2])
836+
);
837+
const xHigh = Math.min(
838+
Math.max(rect1[0], rect1[2]),
839+
Math.max(rect2[0], rect2[2])
840+
);
841+
if (xLow > xHigh) {
854842
return null;
855843
}
856-
857-
// Y: first and second points belong to different rectangles?
858-
if (
859-
(orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) ||
860-
(orderedY[0] === rect2[1] && orderedY[1] === rect1[1])
861-
) {
862-
// Intersection must be between second and third points
863-
result[1] = orderedY[1];
864-
result[3] = orderedY[2];
865-
} else {
844+
const yLow = Math.max(
845+
Math.min(rect1[1], rect1[3]),
846+
Math.min(rect2[1], rect2[3])
847+
);
848+
const yHigh = Math.min(
849+
Math.max(rect1[1], rect1[3]),
850+
Math.max(rect2[1], rect2[3])
851+
);
852+
if (yLow > yHigh) {
866853
return null;
867854
}
868855

869-
return result;
856+
return [xLow, yLow, xHigh, yHigh];
870857
}
871858

872859
// From https://github.com/adobe-webplatform/Snap.svg/blob/b365287722a72526000ac4bfcf0ce4cac2faa015/src/path.js#L852

0 commit comments

Comments
 (0)