Skip to content

Commit ece2dcc

Browse files
perf: memoize segment convention detection (#153)
1 parent 9bad6b3 commit ece2dcc

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/Validator/ConventionDetector.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,15 @@
2525
*/
2626
final class ConventionDetector
2727
{
28+
/**
29+
* Cache of matched conventions per segment string. Segments (e.g. "label",
30+
* "title") repeat heavily across keys, so caching avoids re-running every
31+
* convention regex for the same segment.
32+
*
33+
* @var array<string, array<string>>
34+
*/
35+
private array $segmentConventionCache = [];
36+
2837
/**
2938
* Detect which conventions a key matches.
3039
*
@@ -84,6 +93,10 @@ public function detectKeyConventions(string $key): array
8493
*/
8594
public function detectSegmentConventions(string $segment): array
8695
{
96+
if (isset($this->segmentConventionCache[$segment])) {
97+
return $this->segmentConventionCache[$segment];
98+
}
99+
87100
$matchingConventions = [];
88101

89102
foreach (KeyNamingConvention::cases() as $convention) {
@@ -97,7 +110,7 @@ public function detectSegmentConventions(string $segment): array
97110
$matchingConventions[] = 'unknown';
98111
}
99112

100-
return $matchingConventions;
113+
return $this->segmentConventionCache[$segment] = $matchingConventions;
101114
}
102115

103116
/**

tests/src/Validator/ConventionDetectorTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ protected function setUp(): void
3333
$this->detector = new ConventionDetector();
3434
}
3535

36+
public function testDetectSegmentConventionsIsMemoized(): void
37+
{
38+
$first = $this->detector->detectSegmentConventions('label');
39+
$second = $this->detector->detectSegmentConventions('label');
40+
41+
$this->assertSame($first, $second);
42+
}
43+
3644
/**
3745
* @param array<string> $expectedContains
3846
* @param array<string> $expectedNotContains

0 commit comments

Comments
 (0)