Subject: | Patch: speed up PDF::API2::Resource::BaseFont::width |
Speed up PDF::API2::Resource::BaseFont::width by caching results of wxByEnc() method call and taking conditional outside of the loop.
Subject: | speed-up-width-patch.txt |
diff --git a/lib/PDF/API2/Resource/BaseFont.pm b/lib/PDF/API2/Resource/BaseFont.pm
index 1d974b6..4e31b55 100644
--- a/lib/PDF/API2/Resource/BaseFont.pm
+++ b/lib/PDF/API2/Resource/BaseFont.pm
@@ -624,17 +624,25 @@ is used either in native or utf8 format (check utf8-flag).
sub width {
my ($self,$text)=@_;
my $width=0;
+ my @widths_cache;
if(is_utf8($text)) {
$text=$self->strByUtf($text)
}
- my $lastglyph='';
- foreach my $n (unpack('C*',$text))
- {
- $width+=$self->wxByEnc($n);
- if($self->{-dokern} && ref($self->data->{kern}))
+ if ($self->{-dokern} && ref($self->data->{kern})) {
+ my $lastglyph='';
+ foreach my $n (unpack('C*',$text))
{
- $width+=$self->data->{kern}->{$lastglyph.':'.$self->data->{e2n}->[$n]};
- $lastglyph=$self->data->{e2n}->[$n];
+ $width += ($widths_cache[$n] //= $self->wxByEnc($n));
+ if($self->{-dokern} && ref($self->data->{kern}))
+ {
+ $width+=$self->data->{kern}->{$lastglyph.':'.$self->data->{e2n}->[$n]};
+ $lastglyph=$self->data->{e2n}->[$n];
+ }
+ }
+ } else {
+ foreach my $n (unpack('C*',$text))
+ {
+ $width += ($widths_cache[$n] //= $self->wxByEnc($n));
}
}
$width/=1000;