Skip to content

Commit

Permalink
PERF: Incorrect memoization in `ActiveRecord::Associations::Preloader…
Browse files Browse the repository at this point in the history
…::Association`.

```
require 'active_record'
require 'benchmark/ips'

ActiveRecord::Base.establish_connection(ENV.fetch('DATABASE_URL'))
ActiveRecord::Migration.verbose = false

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
    t.string :name, :email
    t.integer :topic_id
    t.timestamps null: false
  end

  create_table :topics, force: true do |t|
    t.string :title
    t.timestamps null: false
  end
end

attributes = {
  name: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
  email: 'foobar@email.com'
}

class Topic < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :topic
end

100.times do
  User.create!(attributes)
end

users = User.first(50)

100.times do
  Topic.create!(title: 'This is a topic', users: users)
end

Benchmark.ips do |x|
  x.config(time: 10, warmup: 5)

  x.report("preload") do
    User.includes(:topic).all.to_a
  end
end
```

```
Calculating -------------------------------------
             preload    25.000  i/100ms
-------------------------------------------------
             preload    251.772  (± 1.2%) i/s -      2.525k
```

```
Calculating -------------------------------------
             preload    26.000  i/100ms
-------------------------------------------------
             preload    270.392  (± 1.1%) i/s -      2.704k
```
  • Loading branch information
tgxworld committed Sep 11, 2017
1 parent ee79f00 commit 32e1e70
Showing 1 changed file with 5 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ def owners_by_key
end

def key_conversion_required?
@key_conversion_required ||= association_key_type != owner_key_type
unless defined?(@key_conversion_required)
@key_conversion_required = (association_key_type != owner_key_type)
end

@key_conversion_required
end

def convert_key(key)
Expand Down

0 comments on commit 32e1e70

Please sign in to comment.