Last active
December 13, 2015 20:08
-
-
Save kiennt/4967466 to your computer and use it in GitHub Desktop.
Pre define method for array sort
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' | |
Benchmark.bm do |x| | |
names = ["matz", "rossum", "ryal", "ritchie", "brendan"] | |
n = 50000 | |
x.report "method missing" do | |
class Array | |
def method_missing name, *argv | |
super unless name =~ /^sort_by_(\w+)_(asc|desc)$/ | |
condition = ($2 == "asc" ? "{ |a, b| a.%s <=> b.%s }" : "{ |a, b| b.%s <=> a.%s }") % [$1, $1] | |
instance_eval "sort #{condition}" | |
end | |
end | |
n.times { names.sort_by_length_asc } | |
end | |
x.report "predefine method" do | |
class Array | |
def method_missing name, *argv | |
super unless name =~ /^sort_by_(\w+)_(asc|desc)$/ | |
condition = ($2 == "asc" ? "{ |a, b| a.%s <=> b.%s }" : "{ |a, b| b.%s <=> a.%s }") % [$1, $1] | |
Array.class_eval <<-METHOD | |
def #{name} | |
sort #{condition} | |
end | |
METHOD | |
instance_eval "#{name}" | |
end | |
end | |
n.times { names.sort_by_length_asc } | |
end | |
end |
huydx
commented
Feb 16, 2013
require 'benchmark'
require 'ruby-prof'
names = ["matz", "rossum", "ryal", "ritchie", "brendan"]
n = 5000
class Array
def method_missing name, *argv
super unless name =~ /^sort_by_(¥w+)_(asc|desc)$/
condition = ($2 == "asc" ? "{ |a, b| a.%s <=> b.%s }" : "{ |a, b| b.%s <=> a.%s }") % [$1, $1]
Array.class_eval <<-METHOD
def #{name}
sort #{condition}
end
METHOD
instance_eval "#{name}"
end
end
RubyProf.start
n.times { names.sort_by_length_asc }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)
Array.send :remove_method, :sort_by_length_asc
class Array
def method_missing name, *argv
super unless name =~ /^sort_by_(¥w+)_(asc|desc)$/
condition = ($2 == "asc" ? "{ |a, b| a.%s <=> b.%s }" : "{ |a, b| b.%s <=> a.%s }") % [$1, $1]
instance_eval "sort #{condition}"
end
end
RubyProf.start
n.times { names.sort_by_length_asc }
result = RubyProf.stop
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment