Skip to content

Commit 3222a85

Browse files
Performance optimization: Cache attribute_names Set
- Add attribute_names_set class method with memoization - Use cached Set in assign_attributes instead of converting on each call - Eliminates O(m) Set conversion overhead, where m = number of attributes - Maintains O(1) lookup performance for unknown attribute detection - All 14 tests pass
1 parent d763a15 commit 3222a85

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

lib/couchbase-orm/base.rb

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ class MismatchTypeError < RuntimeError; end
5858
# Set to false to silently ignore unknown attributes during mass assignment
5959
class_attribute :raise_on_unknown_attributes, default: true
6060

61+
# Returns a cached Set of attribute names for efficient lookup
62+
# This avoids repeated array-to-set conversions in assign_attributes
63+
def self.attribute_names_set
64+
@attribute_names_set ||= attribute_names.to_set
65+
end
66+
6167
def initialize(model = nil, ignore_doc_type: false, **attributes)
6268
CouchbaseOrm.logger.debug { "Initialize model #{model} with #{attributes.to_s.truncate(200)}" }
6369
@__metadata__ = Metadata.new
@@ -124,13 +130,12 @@ def assign_attributes(hash)
124130
if self.class.raise_on_unknown_attributes
125131
super(hash.except("type"))
126132
else
127-
# Filter unknown attributes
133+
# Filter unknown attributes using cached Set for O(1) lookups
128134
known_names = self.class.attribute_names
129135
known_attrs = hash.slice(*known_names)
130136

131-
# Use a Set for efficient lookup of unknown keys
132-
known_names_set = known_names.to_set
133-
unknown_keys = hash.keys.reject { |k| known_names_set.include?(k) || k == "type" }
137+
# Use cached Set for efficient O(1) lookup of unknown keys
138+
unknown_keys = hash.keys.reject { |k| self.class.attribute_names_set.include?(k) || k == "type" }
134139

135140
if unknown_keys.any?
136141
CouchbaseOrm.logger.warn "Ignoring unknown attribute(s) for #{self.class.name}: #{unknown_keys.join(', ')}"

0 commit comments

Comments
 (0)