Skip to content

Commit

Permalink
Speed up strongRound by avoiding string casting (#1716)
Browse files Browse the repository at this point in the history
I'm currently profiling my build pipeline and noticed that the
`strongRound` function showed up a couple of times, followed immediately
with a bit of GC cleanup shortly after. We can speed up that function by
avoiding the string casting caused by `Number.prototype.toFixed()`.

In my project's build pipeline with lots of svg icons this saves about
1.4s in total.

<img width="792" alt="js-tools-strongRound"
src="https://user-images.githubusercontent.com/1062408/204393563-666be3e0-e0ee-4608-9b7d-9ea8352bd36b.png">
  • Loading branch information
marvinhagemeister authored Nov 30, 2022
1 parent ae32acf commit c641da2
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions plugins/convertPathData.js
Original file line number Diff line number Diff line change
Expand Up @@ -951,6 +951,16 @@ function getIntersection(coords) {
}
}

/**
* Does the same as `Number.prototype.toFixed` but without casting
* the return value to a string.
* @type {(num: number, precision: number) => number}
*/
function toFixed(num, precision) {
const pow = 10 ** precision;
return Math.round(num * pow) / pow;
}

/**
* Decrease accuracy of floating-point numbers
* in path data keeping a specified number of decimals.
Expand All @@ -960,16 +970,14 @@ function getIntersection(coords) {
* @type {(data: number[]) => number[]}
*/
function strongRound(data) {
for (var i = data.length; i-- > 0; ) {
// @ts-ignore
if (data[i].toFixed(precision) != data[i]) {
// @ts-ignore
var rounded = +data[i].toFixed(precision - 1);
const precisionNum = precision || 0;
for (let i = data.length; i-- > 0; ) {
const fixed = toFixed(data[i], precisionNum);
if (fixed !== data[i]) {
const rounded = toFixed(data[i], precisionNum - 1);
data[i] =
// @ts-ignore
+Math.abs(rounded - data[i]).toFixed(precision + 1) >= error
? // @ts-ignore
+data[i].toFixed(precision)
toFixed(Math.abs(rounded - data[i]), precisionNum + 1) >= error
? fixed
: rounded;
}
}
Expand Down

0 comments on commit c641da2

Please sign in to comment.