Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Created August 14, 2015 08:16
Show Gist options
  • Save benoittgt/c6ce59f14ac6c0ce1f8e to your computer and use it in GitHub Desktop.
Save benoittgt/c6ce59f14ac6c0ce1f8e to your computer and use it in GitHub Desktop.
Difference between active record and sql for with/without request
#In pry-rails on my rails project
require 'benchmark/ips'
Benchmark.ips do |x|
x.report("sql request") { User.where("EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (?))", [8939, 8950]).where("NOT EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (?))", [8942]).count
x.report("active record") { (User.joins(:groups).where(groups: {id: ["8939","8950"]}) - User.joins(:groups).where(groups: {id: 8942})).count }
x.compare!
end
# Comparison:
# sql request: 299.4 i/s
# active record: 123.6 i/s - 2.42x slower
=> #<Benchmark::IPS::Report:0x007fe0517c1008
@data=nil,
@entries=
[#<Benchmark::IPS::Report::Entry:0x007fe04f7a9158 @ips=299.353570090315, @ips_sd=41, @iterations=1479, @label="sql request", @measurement_cycle=29, @microseconds=5037948.6083984375, @show_total_time=false>,
#<Benchmark::IPS::Report::Entry:0x007fe050e004b0 @ips=123.57053401687592, @ips_sd=13, @iterations=612, @label="active record", @measurement_cycle=12, @microseconds=5004271.2688446045, @show_total_time=false>]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment