Skip to content

Commit

Permalink
fix a couple perf bottlenecks
Browse files Browse the repository at this point in the history
  • Loading branch information
Rennzie committed Sep 22, 2023
1 parent 3ffe482 commit 34a2a01
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
31 changes: 24 additions & 7 deletions js/geodesy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,7 @@ function prepareCoordinates(
const flatCoords = flattenCoords(coordinates);

// Move the coordinates into WASM memory
const coordBufPtr = new GeodesyWasm.CoordBuffer(
new Float64Array(flatCoords),
dimensions,
);
const coordBufPtr = new GeodesyWasm.CoordBuffer(flatCoords, dimensions);

return [coordBufPtr, dimensions];
}
Expand Down Expand Up @@ -139,18 +136,38 @@ function dimensionsAreConsistent(
}
}

function flattenCoords(coords: number[][]): number[] {
return coords.reduce((acc, val) => acc.concat(val), []);
function flattenCoords(coords: number[][]): Float64Array {
const dimension = coords[0].length;
const res = new Float64Array(coords.length * dimension);

// Fastest way to flatten an array while creating a Float64Array
// It's faster than using Float64Array.set() because it avoids the overhead of
// creating a new Float64Array each item.
let index = 0;
for (let i = 0; i < coords.length; i++) {
for (let j = 0; j < dimension; j++) {
res[index++] = coords[i][j];
}
}
return res;
}

function unflattenCoords(
coords: Float64Array,
dimensions: GeodesyWasm.CoordDimension,
): number[][] {
const dim = dimensions === GeodesyWasm.CoordDimension.Two ? 2 : 3;

// This is the fastest way to unflatten an array.
// It's faster than using Array.from(coords.subarray(i, i + dim)) because it avoids the overhead of
// creating a new a Float64Array on each item and calling subarray on it.
const res: number[][] = [];
for (let i = 0; i < coords.length; i += dim) {
res.push(Array.from(coords.subarray(i, i + dim)));
const row: number[] = [];
for (let j = 0; j < dim; j++) {
row.push(coords[i + j]);
}
res.push(row);
}
return res;
}
Expand Down
4 changes: 2 additions & 2 deletions src/geodesy/coordinate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ impl CoordBuffer {
pub fn into_array(self) -> js_sys::Float64Array {
let array = js_sys::Float64Array::new_with_length(self.0.buffer.len() as u32);

for (i, v) in self.0.buffer.iter().enumerate() {
array.set_index(i as u32, *v);
for (i, v) in self.0.buffer.into_iter().enumerate() {
array.set_index(i as u32, v);
}

array
Expand Down

0 comments on commit 34a2a01

Please sign in to comment.