Skip to content

Commit bec3bd4

Browse files
committed
Cache LineString.getCoordinates() to avoid redundant array copies
addStartEndCoordinatesToLineString and removeStartEndCoordinatesFromLineString called lineString.getCoordinates() 3-4 times each per invocation. Each call copies the internal PackedCoordinateSequence to a new Coordinate[], creating redundant garbage. Cache the result in a local variable and use System.arraycopy.
1 parent ca1efb2 commit bec3bd4

1 file changed

Lines changed: 10 additions & 12 deletions

File tree

street/src/main/java/org/opentripplanner/street/geometry/GeometryUtils.java

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -105,21 +105,19 @@ public static LineString addStartEndCoordinatesToLineString(
105105
LineString lineString,
106106
Coordinate endCoord
107107
) {
108-
Coordinate[] coordinates = new Coordinate[lineString.getCoordinates().length + 2];
109-
coordinates[0] = startCoord;
110-
for (int j = 0; j < lineString.getCoordinates().length; j++) {
111-
coordinates[j + 1] = lineString.getCoordinates()[j];
112-
}
113-
coordinates[lineString.getCoordinates().length + 1] = endCoord;
114-
return makeLineString(coordinates);
108+
Coordinate[] c = lineString.getCoordinates();
109+
Coordinate[] result = new Coordinate[c.length + 2];
110+
result[0] = startCoord;
111+
System.arraycopy(c, 0, result, 1, c.length);
112+
result[c.length + 1] = endCoord;
113+
return makeLineString(result);
115114
}
116115

117116
public static LineString removeStartEndCoordinatesFromLineString(LineString lineString) {
118-
Coordinate[] coordinates = new Coordinate[lineString.getCoordinates().length - 2];
119-
for (int j = 1; j < lineString.getCoordinates().length - 1; j++) {
120-
coordinates[j - 1] = lineString.getCoordinates()[j];
121-
}
122-
return makeLineString(coordinates);
117+
Coordinate[] c = lineString.getCoordinates();
118+
Coordinate[] result = new Coordinate[c.length - 2];
119+
System.arraycopy(c, 1, result, 0, c.length - 2);
120+
return makeLineString(result);
123121
}
124122

125123
public static GeometryFactory getGeometryFactory() {

0 commit comments

Comments
 (0)