diff options
author | Guo Xiang Tan <tgx_world@hotmail.com> | 2017-09-08 22:30:39 +0800 |
---|---|---|
committer | Guo Xiang Tan <tgx_world@hotmail.com> | 2017-09-26 08:37:06 +0800 |
commit | e03c9066ff83cac409281d6fc5e2377493009364 (patch) | |
tree | f56494823ac1fc3f05ed0f58c1ba7812a1253349 /activerecord/lib/active_record/attribute_methods/primary_key.rb | |
parent | 1689d9dbb228e427193bf5f32325bd8d2b87aa9e (diff) | |
download | rails-e03c9066ff83cac409281d6fc5e2377493009364.tar.gz rails-e03c9066ff83cac409281d6fc5e2377493009364.tar.bz2 rails-e03c9066ff83cac409281d6fc5e2377493009364.zip |
PERF: Partially recover some performance when preloading.
Benchmark Script:
```
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)
Topic.create!(title: 'This is a topic', users: users)
Benchmark.ips do |x|
x.config(time: 10, warmup: 5)
x.report("preload") do
User.includes(:topic).all.to_a
end
end
```
Before:
```
Calculating -------------------------------------
preload 40.000 i/100ms
-------------------------------------------------
preload 407.962 (± 1.5%) i/s - 4.080k
```
After:
```
alculating -------------------------------------
preload 43.000 i/100ms
-------------------------------------------------
preload 427.567 (± 1.6%) i/s - 4.300k
```
Diffstat (limited to 'activerecord/lib/active_record/attribute_methods/primary_key.rb')
-rw-r--r-- | activerecord/lib/active_record/attribute_methods/primary_key.rb | 6 |
1 files changed, 4 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 63c059e291..d8fc046e10 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -17,13 +17,15 @@ module ActiveRecord # Returns the primary key value. def id sync_with_transaction_state - _read_attribute(self.class.primary_key) if self.class.primary_key + primary_key = self.class.primary_key + _read_attribute(primary_key) if primary_key end # Sets the primary key value. def id=(value) sync_with_transaction_state - _write_attribute(self.class.primary_key, value) if self.class.primary_key + primary_key = self.class.primary_key + _write_attribute(primary_key, value) if primary_key end # Queries the primary key value. |