Skip to content

Commit

Permalink
Cache the index calls for better performance
Browse files Browse the repository at this point in the history
  • Loading branch information
Toflar committed Aug 18, 2023
1 parent 4096d89 commit a4277c0
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/StateSetIndex.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@

class StateSetIndex
{
/**
* @var array<string, int>
*/
private array $indexCache = [];

public function __construct(
private Config $config,
private AlphabetInterface $alphabet,
Expand Down Expand Up @@ -40,6 +45,11 @@ public function index(array $strings): array
$assigned = [];

foreach ($strings as $string) {
if (isset($this->indexCache[$string])) {
$assigned[$string] = $this->indexCache[$string];
continue;
}

$state = 0;
$this->loopOverEveryCharacter($string, function (int $mappedChar) use (&$state) {
$newState = (int) ($state * $this->config->getAlphabetSize() + $mappedChar);
Expand All @@ -48,7 +58,7 @@ public function index(array $strings): array
$state = $newState;
});

$assigned[$string] = $state;
$assigned[$string] = $this->indexCache[$string] = $state;
$this->stateSet->acceptString($state, $string);
}

Expand Down

0 comments on commit a4277c0

Please sign in to comment.