Skip to content

Instantly share code, notes, and snippets.

@jah2488
Created February 6, 2014 15:17
Show Gist options
  • Save jah2488/8846147 to your computer and use it in GitHub Desktop.
Save jah2488/8846147 to your computer and use it in GitHub Desktop.
Rough benchmarking of running the (roughly) equivalent sorting code in ruby vs sql
require 'active_record'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection 'sqlite3:///:memory:'
ActiveRecord::Schema.define do
create_table(:posts) { |t| t.string :name }
create_table(:comments) { |t| t.integer :post_id }
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
10000.times do |pi|
p = Post.create!(:name => ->{Array.new(10){[*'a'..'z'].sample }.join}[])
3.times { Comment.create!(:post_id => p.id) }
end
require 'pry'
require 'benchmark'
binding.pry
Benchmark.bm(7) do |x|
x.report("SQL:") { (1..100).each { Post.find_by_sql('SELECT posts.* FROM posts ORDER BY posts.name ASC;') }}
x.report("AREL:") { (1..100).each { Post.all.sort_by(&:name) }}
x.report("RUBY:") { (1..100).each { Post.all.to_a.sort_by(&:name)}}
end
user system total real
#SQL: 18.540000 0.160000 18.700000 ( 18.756530)
#AREL: 20.160000 0.180000 20.340000 ( 20.396667)
#RUBY: 21.160000 0.170000 21.330000 ( 21.441187)
@jah2488
Copy link
Author

jah2488 commented Feb 6, 2014

While this was running I checked on my CPU
cpu
and on the ram usage
ram

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment