From 57d35b2bf9e48173a5f97ccff5e6897f0c46411f Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 2 Mar 2015 07:51:29 -0800 Subject: call `sync_with_transaction_state` inside `persisted?` then check ivars directly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 ``` --- activerecord/lib/active_record/persistence.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/persistence.rb') 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. -- cgit v1.2.3