Created
April 4, 2016 11:14
-
-
Save ccocchi/8d0bb144bd4f9631b7a63c21c75de7fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Author
ccocchi
commented
Apr 4, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment