Skip to content

Commit 6cd42c0

Browse files
committed
Merge pull request #10 from JasonBarnabe/typecastperf
Cache xpath calls in typecast
2 parents dd64bed + 7d4e345 commit 6cd42c0

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

lib/qbxml/hash.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ def self.xml_to_hash(node, hash = {}, opts = {})
7575
node_hash = {CONTENT_ROOT => '', ATTR_ROOT => {}}
7676
name = node.name
7777
schema = opts[:schema]
78+
opts[:typecast_cache] ||= {}
7879

7980
# Insert node hash into parent hash correctly.
8081
case hash[name]
@@ -105,7 +106,7 @@ def self.xml_to_hash(node, hash = {}, opts = {})
105106
node_hash.delete(ATTR_ROOT)
106107
hash[name] = \
107108
if schema
108-
typecast(schema, node.path, node_hash[CONTENT_ROOT])
109+
typecast(schema, node.path, node_hash[CONTENT_ROOT], opts[:typecast_cache])
109110
else
110111
node_hash[CONTENT_ROOT]
111112
end
@@ -119,9 +120,10 @@ def self.xml_to_hash(node, hash = {}, opts = {})
119120

120121
private
121122

122-
def self.typecast(schema, xpath, value)
123+
def self.typecast(schema, xpath, value, typecast_cache)
123124
type_path = xpath.gsub(/\[\d+\]/,'')
124-
type_proc = Qbxml::TYPE_MAP[schema.xpath(type_path).first.try(:text)]
125+
# This is fairly expensive. Cache it for better performance when parsing lots of records of the same type.
126+
type_proc = typecast_cache[type_path] ||= Qbxml::TYPE_MAP[schema.xpath(type_path).first.try(:text)]
125127
raise "#{xpath} is not a valid type" unless type_proc
126128
type_proc[value]
127129
end

0 commit comments

Comments
 (0)