Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Memoize Database Field Names For Faster Fields Access #5809

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/mongoid/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,8 @@ def attribute_names
#
# @return [ String ] The name of the field as it's stored in the db.
def database_field_name(name)
Fields.database_field_name(name, relations, aliased_fields, aliased_associations)
@database_field_names ||= {}
@database_field_names[name] ||= Fields.database_field_name(name, relations, aliased_fields, aliased_associations)
end

# Defines all the fields that are accessible on the Document
Expand Down Expand Up @@ -561,6 +562,7 @@ def add_defaults(field)
#
# @api private
def add_field(name, options = {})
@database_field_names[name] = nil if @database_field_names
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious what the purpose of this line is; is this resetting some previously set field? If it's just for initialization, I'd prefer to leave it out, since the field would be nil implicitly, by default.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's meant as some sort of cache busting.
This is in case something unexpected like adding a field happens after we have accessed that field, for example, we have accessed field abc earlier as an alias, but later in the lifecycle, somehow that field added as an actual field.
I'm not certain about the exact flow, but perhaps we should also revoke the value for any alias that field might have.

aliased = options[:as]
aliased_fields[aliased.to_s] = name if aliased
field = field_for(name, options)
Expand Down