Created
September 1, 2011 15:26
-
-
Save titanous/1186418 to your computer and use it in GitHub Desktop.
This file contains 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' | |
module Arel | |
module Nodes | |
class Ordering | |
end | |
end | |
end | |
def old_reverse_sql_order(order_query) | |
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty? | |
order_query.map do |o| | |
case o | |
when Arel::Nodes::Ordering | |
o.reverse | |
when String, Symbol | |
o.to_s.split(',').collect do |s| | |
s.strip! | |
s.gsub!(/\sasc\Z/i, ' DESC') || s.gsub!(/\sdesc\Z/i, ' ASC') || s.concat(' DESC') | |
end | |
else | |
o | |
end | |
end.flatten | |
end | |
def new_reverse_sql_order(order_query) | |
order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty? | |
order_query.map do |o| | |
case o | |
when Arel::Nodes::Ordering | |
o.reverse | |
when String, Symbol | |
s = o.to_s.gsub(/\s((desc)|(asc))\s*(,|\Z)/i) { |m| " #{$2 ? 'ASC' : 'DESC'}#{$4}" } | |
s.match(/\s(de|a)sc\Z/i) ? s : s.concat(" DESC") | |
else | |
o | |
end | |
end.flatten | |
end | |
query = ['SELECT "tests".* FROM "tests" ORDER BY COALESCE(updated_at, created_at) ASC LIMIT 1'] | |
n = 10_000 | |
Benchmark.bmbm do |x| | |
x.report('old') { n.times { old_reverse_sql_order(query) } } | |
x.report('new') { n.times { new_reverse_sql_order(query) } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment