Skip to content

Fix method_missing performance regression for virtual SELECT alias attributes - #57226

Merged
skipkayhil merged 1 commit into
rails:mainfrom
hammadxcm:fix-method-missing-name-error-perf-regression
Aug 13, 2026
Merged

skipkayhil merged 1 commit into
rails:mainfrom
hammadxcm:fix-method-missing-name-error-perf-regression

Conversation

@hammadxcm

Copy link
Copy Markdown
Contributor

Motivation / Background

Fixes #57183.

PR #53890 (shipped in 7.2.3) changed method_missing in ActiveRecord::AttributeMethods to call self.class.public_instance_method(name), which raises and rescues NameError for virtual SELECT alias attributes (not backed by real columns). Exception allocation + backtrace capture costs ~9μs per call, causing a ~3x regression in virtual attribute access.

Solution

Guard public_instance_method with public_method_defined? — a zero-allocation boolean check — so the NameError path is never hit for virtual attributes. The thread-safety properties introduced in #53890 are fully preserved since public_method_defined? is a simple lookup on the method table that define_attribute_methods just populated.

Benchmark

50,000 attribute accesses (SQLite, virtual SELECT alias)

                              Before (7.2.3)    After (this PR)
Real column (.latitude):          0.004s             0.010s
Virtual attr (.virtual_attr):     0.189s             0.077s
Virtual / Real ratio:             42.1x              7.9x

Checklist

  • CHANGELOG entry added
  • Tests added for virtual SELECT alias attribute access
  • Existing attribute_methods test suite passes (137 runs, 624 assertions, 0 failures)
  • Finder, base, and calculations tests pass

…tributes

Guard `public_instance_method` call with `public_method_defined?` to
avoid raising and rescuing `NameError` for attributes not backed by
real columns (e.g. `SELECT 42 AS virtual_attr`).

The `NameError` exception allocation + backtrace capture costs ~9μs per
call, causing a ~3x regression introduced in rails#53890. This restores
performance by using a cheap boolean check on the common path.

Fixes rails#57183.
@skipkayhil
skipkayhil force-pushed the fix-method-missing-name-error-perf-regression branch from 8104d00 to 56f67b9 Compare August 13, 2026 03:10
@hmcguire-shopify

hmcguire-shopify commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

More thorough benchmark:

require "benchmark/ips"
require "active_record"

STAGE = ENV.fetch("STAGE", "after")

ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.lease_connection.create_table(:posts) { |t| t.string :title }
class Post < ActiveRecord::Base; end

row   = Post.create!(title: "x")
extra = Post.select("id, title, 10 as tenderlove").first

CASES = {
  "title"      => -> { row.title },        # attribute method
  "tenderlove" => -> { extra.tenderlove }, # dynamic attribute
}

CASES.each do |label, block|
  puts
  Benchmark.ips do |x|
    x.config(time: 3, warmup: 1)
    x.save!("/tmp/bench_#{label}.hold")
    x.report("#{label} (#{STAGE})") { block.call }
    x.compare!
  end
end
$ STAGE=after bx ruby --yjit activemodel/bench_attribute_method_patterns.rb

ruby 4.0.6 (2026-07-14 revision 03b6d3f889) +YJIT +PRISM [arm64-darwin23]
Warming up --------------------------------------
       title (after)     1.900M i/100ms
Calculating -------------------------------------
       title (after)     20.222M (± 1.7%) i/s   (49.45 ns/i) -     60.804M in   3.006844s

Comparison:
 title (after): 20221707.5 i/s
title (before): 20074094.1 i/s - same-ish: difference falls within error


ruby 4.0.6 (2026-07-14 revision 03b6d3f889) +YJIT +PRISM [arm64-darwin23]
Warming up --------------------------------------
  tenderlove (after)   128.383k i/100ms
Calculating -------------------------------------
  tenderlove (after)      1.308M (± 1.5%) i/s  (764.56 ns/i) -      3.980M in   3.042859s

Comparison:
 tenderlove (after):  1307938.7 i/s
tenderlove (before):   733007.2 i/s - 1.78x  slower

This theoretically could slow down the first caller of a column if attribute methods aren't defined, but once defined this only improves the performance of virtual columns 👍

@skipkayhil
skipkayhil merged commit d743cf0 into rails:main Aug 13, 2026
3 checks passed
skipkayhil added a commit that referenced this pull request Aug 13, 2026
…r-perf-regression

Fix method_missing performance regression for virtual SELECT alias attributes
skipkayhil added a commit that referenced this pull request Aug 13, 2026
…r-perf-regression

Fix method_missing performance regression for virtual SELECT alias attributes
skipkayhil added a commit that referenced this pull request Aug 13, 2026
…r-perf-regression

Fix method_missing performance regression for virtual SELECT alias attributes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Performance regression: method_missing raises NameError for virtual SELECT alias attributes

3 participants