Skip to content

Instantly share code, notes, and snippets.

@ccocchi
Created April 4, 2016 11:14
Show Gist options
  • Save ccocchi/8d0bb144bd4f9631b7a63c21c75de7fd to your computer and use it in GitHub Desktop.
Save ccocchi/8d0bb144bd4f9631b7a63c21c75de7fd to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
module TestMethods
def order_by_ids(ids)
order("idx(ARRAY#{ids}, id)")
end
def order_by_ids_string(ids)
o = Post.send(:sanitize_sql_array,
["position(id::text in ?)", ids.join(',')]
)
order(o)
end
def order_by_ids_string_fast(ids)
order("position(id::text in '#{ids.join(',')}')")
end
def to_ordered_ary(ids)
ids.map!(&:to_i)
# self.select_values += [:id]
to_a.index_by(&:id).values_at(*ids)
end
end
ActiveRecord::Relation.send(:include, TestMethods)
ids = [80, 91, 87, 90, 86, 93, 92, 85, 84, 81, 79]
scp = Post.where(id: ids).select(:id)
Benchmark.ips do |x|
x.report('intarray') { scp.order_by_ids(ids).to_a }
x.report('position') { scp.order_by_ids_string(ids).to_a }
x.report('position2') { scp.order_by_ids_string_fast(ids).to_a }
x.report('ruby') { scp.to_ordered_ary(ids) }
x.compare!
end
@ccocchi
Copy link
Author

ccocchi commented Apr 4, 2016

Comparison:
                ruby:    96370.1 i/s
           position2:      725.5 i/s - 132.83x slower
            intarray:      708.7 i/s - 135.99x slower
            position:      690.4 i/s - 139.58x slower

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