Skip to content

Commit

Permalink
Merge pull request #663 from amomchilov/optimize-object_id-use
Browse files Browse the repository at this point in the history
`YAMLTree` performance by not using `object_id`s
  • Loading branch information
tenderlove authored Dec 18, 2023
2 parents 02b7ef3 + 0dc25a9 commit 21f051b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 12 deletions.
13 changes: 6 additions & 7 deletions lib/psych/visitors/yaml_tree.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,29 @@ module Visitors
class YAMLTree < Psych::Visitors::Visitor
class Registrar # :nodoc:
def initialize
@obj_to_id = {}
@obj_to_node = {}
@obj_to_id = {}.compare_by_identity
@obj_to_node = {}.compare_by_identity
@targets = []
@counter = 0
end

def register target, node
return unless target.respond_to? :object_id
@targets << target
@obj_to_node[target.object_id] = node
@obj_to_node[target] = node
end

def key? target
@obj_to_node.key? target.object_id
@obj_to_node.key? target
rescue NoMethodError
false
end

def id_for target
@obj_to_id[target.object_id] ||= (@counter += 1)
@obj_to_id[target] ||= (@counter += 1)
end

def node_for target
@obj_to_node[target.object_id]
@obj_to_node[target]
end
end

Expand Down
8 changes: 4 additions & 4 deletions test/psych/test_object_references.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def assert_reference_trip obj
rescue Psych::DisallowedClass
data = Psych.unsafe_load yml
end
assert_equal data.first.object_id, data.last.object_id
assert_same data.first, data.last
end

def test_float_references
Expand All @@ -49,7 +49,7 @@ def test_float_references
- *name
eoyml
assert_equal data.first, data.last
assert_equal data.first.object_id, data.last.object_id
assert_same data.first, data.last
end

def test_binary_references
Expand All @@ -60,7 +60,7 @@ def test_binary_references
- *name
eoyml
assert_equal data.first, data.last
assert_equal data.first.object_id, data.last.object_id
assert_same data.first, data.last
end

def test_regexp_references
Expand All @@ -70,7 +70,7 @@ def test_regexp_references
- *name
eoyml
assert_equal data.first, data.last
assert_equal data.first.object_id, data.last.object_id
assert_same data.first, data.last
end
end
end
2 changes: 1 addition & 1 deletion test/psych/visitors/test_to_ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ def test_alias

list = seq.to_ruby
assert_equal %w{ foo foo }, list
assert_equal list[0].object_id, list[1].object_id
assert_same list[0], list[1]
end

def test_mapping_with_str_tag
Expand Down

0 comments on commit 21f051b

Please sign in to comment.