Skip to content

Commit 9b6a9ae

Browse files
committed
Speed up usage of differences by caching any encountered codepoints (20%-25% speed improvements on samples with differences arrays)
1 parent d16e6cd commit 9b6a9ae

3 files changed

Lines changed: 13 additions & 6 deletions

File tree

src/Document/ContentStream/PositionedText/TextSegment/TextSegment.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public function __construct(
1717
public function getText(?DifferencesArrayValue $differences, ?EncodingNameValue $encoding, ?ToUnicodeCMap $toUnicodeCMap): string {
1818
$binaryString = $this->textString->getBinaryString();
1919
if (strlen($binaryString) === 1 && ($glyph = $differences?->getGlyph(ord($binaryString))) !== null) {
20-
$text = $glyph->getChar();
20+
$text = $glyph;
2121
} elseif (in_array($encoding, [EncodingNameValue::MacExpertEncoding, EncodingNameValue::WinAnsiEncoding], true)
2222
&& $differences === null) {
2323
$text = $encoding->decodeString($binaryString);

src/Document/Dictionary/DictionaryValue/Array/DifferencesArrayValue.php

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
use PrinsFrank\PdfParser\Document\Dictionary\DictionaryValue\Reference\ReferenceValueArray;
1010

1111
class DifferencesArrayValue implements DictionaryValue {
12+
/** @var array<int, string|null> */
13+
private array $glyphCache = [];
14+
1215
/** @param list<DifferenceRange> $differenceRanges */
1316
public function __construct(
1417
private readonly array $differenceRanges,
@@ -44,13 +47,17 @@ public static function fromValue(string $valueString): ?self {
4447
return new self($differenceRanges);
4548
}
4649

47-
public function getGlyph(int $int): ?AGlyphList {
50+
public function getGlyph(int $codePoint): ?string {
51+
if (array_key_exists($codePoint, $this->glyphCache)) {
52+
return $this->glyphCache[$codePoint];
53+
}
54+
4855
foreach ($this->differenceRanges as $differenceRange) {
49-
if ($differenceRange->contains($int)) {
50-
return $differenceRange->getGlyph($int);
56+
if ($differenceRange->contains($codePoint)) {
57+
return $this->glyphCache[$codePoint] = $differenceRange->getGlyph($codePoint)?->getChar();
5158
}
5259
}
5360

54-
return null;
61+
return $this->glyphCache[$codePoint] = null;
5562
}
5663
}

tests/Unit/Document/Dictionary/DictionaryValue/Array/DifferencesArrayValueTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public function testFromValue(): void {
3636

3737
public function testGetGlyph(): void {
3838
static::assertSame(
39-
AglyphList::grave,
39+
"\u{0060}",
4040
(new DifferencesArrayValue([new DifferenceRange(36, [AGlyphList::grave])]))
4141
->getGlyph(36),
4242
);

0 commit comments

Comments
 (0)