Skip to content

Commit

Permalink
Avoid calling "DecodeName" when parsing dictionaries.
Browse files Browse the repository at this point in the history
If no name with a "#" has been added before, it's not necessary to go
through the expensive "Insert" call that will call "DecodeName" for
every previously added key.
  • Loading branch information
fancycode authored and hhrutter committed Jan 25, 2024
1 parent b89d7b1 commit bec27a4
Showing 1 changed file with 23 additions and 3 deletions.
26 changes: 23 additions & 3 deletions pkg/pdfcpu/model/parse.go
Expand Up @@ -530,6 +530,7 @@ func parseName(line *string) (*types.Name, error) {
func processDictKeys(line *string, relaxed bool) (types.Dict, error) {
l := *line
var eol bool
var hasNames bool
d := types.NewDict()
for !strings.HasPrefix(l, ">>") {
key, err := parseName(&l)
Expand Down Expand Up @@ -558,8 +559,18 @@ func processDictKeys(line *string, relaxed bool) (types.Dict, error) {
if log.ParseEnabled() {
log.Parse.Printf("ParseDict: dict[%s]=%v\n", key, obj)
}
if ok := d.Insert(string(*key), obj); !ok {
return nil, errDictionaryDuplicateKey
stringKey := string(*key)
if !hasNames {
// Avoid expensive "DecodeName" on existing keys in "Insert".
if _, found := d[stringKey]; found {
return nil, errDictionaryDuplicateKey
}
d[stringKey] = obj
hasNames = strings.IndexByte(stringKey, '#') >= 0
} else {
if ok := d.Insert(stringKey, obj); !ok {
return nil, errDictionaryDuplicateKey
}
}
continue
}
Expand All @@ -572,7 +583,16 @@ func processDictKeys(line *string, relaxed bool) (types.Dict, error) {
// Specifying the null object as the value of a dictionary entry (7.3.7, "Dictionary Objects")
// hall be equivalent to omitting the entry entirely.
if obj != nil {
d.Insert(string(*key), obj)
stringKey := string(*key)
if !hasNames {
// Avoid expensive "DecodeName" on existing keys in "Insert".
if _, found := d[stringKey]; !found {
d[stringKey] = obj
hasNames = strings.IndexByte(stringKey, '#') >= 0
}
} else {
d.Insert(stringKey, obj)
}
if log.ParseEnabled() {
log.Parse.Printf("ParseDict: dict[%s]=%v\n", key, obj)
}
Expand Down

0 comments on commit bec27a4

Please sign in to comment.