Skip to content

Commit a4277c0

Browse files
committed
Cache the index calls for better performance
1 parent 4096d89 commit a4277c0

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

src/StateSetIndex.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@
88

99
class StateSetIndex
1010
{
11+
/**
12+
* @var array<string, int>
13+
*/
14+
private array $indexCache = [];
15+
1116
public function __construct(
1217
private Config $config,
1318
private AlphabetInterface $alphabet,
@@ -40,6 +45,11 @@ public function index(array $strings): array
4045
$assigned = [];
4146

4247
foreach ($strings as $string) {
48+
if (isset($this->indexCache[$string])) {
49+
$assigned[$string] = $this->indexCache[$string];
50+
continue;
51+
}
52+
4353
$state = 0;
4454
$this->loopOverEveryCharacter($string, function (int $mappedChar) use (&$state) {
4555
$newState = (int) ($state * $this->config->getAlphabetSize() + $mappedChar);
@@ -48,7 +58,7 @@ public function index(array $strings): array
4858
$state = $newState;
4959
});
5060

51-
$assigned[$string] = $state;
61+
$assigned[$string] = $this->indexCache[$string] = $state;
5262
$this->stateSet->acceptString($state, $string);
5363
}
5464

0 commit comments

Comments
 (0)