Skip to content

Commit

Permalink
cache Registry#definitions to avoid object allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
jrochkind committed Dec 4, 2023
1 parent e6d747b commit 1b94c04
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/attr_json/attribute_definition/registry.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ class Registry
def initialize(hash = {})
@name_to_definition = hash.dup
@store_key_to_definition = {}
definitions.each { |d| store_key_index!(d) }

@name_to_definition.values.each { |d| store_key_index!(d) }

@container_attributes_registered = Hash.new { Set.new }
end
Expand Down Expand Up @@ -55,7 +56,8 @@ def store_key_lookup(container_attribute, store_key)
end

def definitions
@name_to_definition.values
# Since we are immutable, we can cache this to avoid allocation in a hot spot
@stored_definitions ||= @name_to_definition.values
end

# Returns all registered attributes as an array of symbols
Expand Down Expand Up @@ -111,6 +113,8 @@ def add!(definition)
end
@name_to_definition[definition.name.to_sym] = definition
store_key_index!(definition)

@stored_definitions = nil
end

def store_key_index!(definition)
Expand Down

0 comments on commit 1b94c04

Please sign in to comment.