Skip to content

Commit 6e2b5ff

Browse files
josharianpokey
andauthored
memoize minimumTokenRankContainingGrapheme (#1825)
minimumTokenRankContainingGrapheme was accidentally quadratic in the number of tokens sharing a grapheme. It was executed for every token, and for each token, it considered every single other token sharing a candidate grapheme. It dominated hat allocation performance for larger numbers of tokens. Memoizing the result by grapheme text makes it linear again. No functional changes. (Confirmed by hat golden tests on another branch.) ## Checklist - [/] I have added [tests](https://www.cursorless.org/docs/contributing/test-case-recorder/) - [/] I have updated the [docs](https://github.com/cursorless-dev/cursorless/tree/main/docs) and [cheatsheet](https://github.com/cursorless-dev/cursorless/tree/main/cursorless-talon/src/cheatsheet) - [/] I have not broken the cheatsheet --------- Co-authored-by: Pokey Rule <755842+pokey@users.noreply.github.com>
1 parent c5ef8fc commit 6e2b5ff

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

packages/cursorless-engine/src/util/allocateHats/HatMetrics.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { CompositeKeyMap, HatStability, TokenHat } from "@cursorless/common";
2-
import { min } from "lodash";
2+
import { memoize, min } from "lodash";
33
import { HatCandidate } from "./allocateHats";
44

55
/**
@@ -50,8 +50,13 @@ export function minimumTokenRankContainingGrapheme(
5050
tokenRank: number,
5151
graphemeTokenRanks: { [key: string]: number[] },
5252
): HatMetric {
53-
return ({ grapheme: { text } }) =>
54-
min(graphemeTokenRanks[text].filter((r) => r > tokenRank)) ?? Infinity;
53+
const coreMetric = memoize((graphemeText: string): number => {
54+
return (
55+
min(graphemeTokenRanks[graphemeText].filter((r) => r > tokenRank)) ??
56+
Infinity
57+
);
58+
});
59+
return ({ grapheme: { text } }) => coreMetric(text);
5560
}
5661

5762
/**

0 commit comments

Comments
 (0)