Joined May 2011
·

Mario Alberto Chavez

Software Engineer at Crowd Interactive
·
Tijuana, Mexico
·
·
·

Posted to ActiveRecord empty? vs count over 1 year ago

Yes, I did it :)

Posted to ActiveRecord empty? vs count over 1 year ago

I ran same benchmark few more times (1000) the SQL query was the same, both issue a COUNT(*) on the users table. My setup was Ruby 2.0.0-p195 with Rails 4.0.0 on a Postgresql DB, I was running a Rails console with production env.

Benchmark.bm do |bm|
  bm.report("count") do
    1000.times{ Identity.where('id>0').count }
  end
  bm.report("empty?") do
    1000.times{ Identity.where('id>0').empty? }
  end
end

The difference was really minimal like:

       user     system      total        real
count  0.280000   0.030000   0.310000 (  0.437411)
empty?  0.280000   0.030000   0.310000 (  0.428984)

But after a few runs count was faster then empty? was:

       user     system      total        real
count  0.290000   0.030000   0.320000 (  0.427957)
empty?  0.310000   0.020000   0.330000 (  0.454032)

So I don't think that the difference between them are related to the way they are coded on Rails, but to the database or the system at all.

count is a method on ActiveRecord::Calculations that issue the COUNT query to the database.

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/calculations.rb#L22

empty? is a method on ActiveRecord::Relation, it first check if the relation has been loaded from the database, if it was then #empty? is evaluated against it, there is no query sent to the database; if it wasn't loaded then, guess what? it sends #count message to ActiveRecord::Calculation.

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation.rb#L244

So at the end if #empty? needs to go to the database it goes thought a #count.

Posted to CoffeeScript console on Chrome over 1 year ago

Hello all;

I posted this tip like 1.5 years ago, I'm not sure if "CoffeeConsole" was around at that time.

But thanks for let me know

Achievements
409 Karma
15,860 Total ProTip Views