diff options
author | Aaron Patterson <aaron.patterson@gmail.com> | 2015-03-02 07:51:29 -0800 |
---|---|---|
committer | Aaron Patterson <aaron.patterson@gmail.com> | 2015-03-02 07:51:29 -0800 |
commit | 57d35b2bf9e48173a5f97ccff5e6897f0c46411f (patch) | |
tree | 90f1eaeaa3c9c0ced33cf27e0d35228eb339b2c1 /activerecord/lib | |
parent | 10058ea2805e2347fe070b937c62c878269d1b1d (diff) | |
download | rails-57d35b2bf9e48173a5f97ccff5e6897f0c46411f.tar.gz rails-57d35b2bf9e48173a5f97ccff5e6897f0c46411f.tar.bz2 rails-57d35b2bf9e48173a5f97ccff5e6897f0c46411f.zip |
call `sync_with_transaction_state` inside `persisted?` then check ivars
directly
calling `sync_with_transaction_state` is not fast, so if we call it
once, we can improve the performance of the `persisted?` method. This
is important because every call to `url_for(model)` will call
`persisted?`, so we want that to be fast.
Here is the benchmark:
```ruby
require 'active_record'
ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:"
ActiveRecord::Base.connection.instance_eval do
create_table(:articles)
end
class Article < ActiveRecord::Base; end
article = Article.new.tap(&:save!)
Benchmark.ips do |x|
x.report("persisted?") do
article.persisted?
end
end
```
Before this patch:
```
$ bundle exec ruby -rbenchmark/ips persisted.rb
Calculating -------------------------------------
persisted? 3.333k i/100ms
-------------------------------------------------
persisted? 51.037k (± 8.2%) i/s - 253.308k
```
After:
```
$ bundle exec ruby -rbenchmark/ips persisted.rb
Calculating -------------------------------------
persisted? 7.172k i/100ms
-------------------------------------------------
persisted? 120.730k (± 5.1%) i/s - 602.448k
```
Diffstat (limited to 'activerecord/lib')
-rw-r--r-- | activerecord/lib/active_record/persistence.rb | 3 |
1 files changed, 2 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 7c076864a3..a6176dffdb 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -96,7 +96,8 @@ module ActiveRecord # Returns true if the record is persisted, i.e. it's not a new record and it was # not destroyed, otherwise returns false. def persisted? - !(new_record? || destroyed?) + sync_with_transaction_state + !(@new_record || @destroyed) end # Saves the model. |