Skip to content

Instantly share code, notes, and snippets.

@kiennt
Last active December 13, 2015 20:08
Show Gist options
  • Save kiennt/4967466 to your computer and use it in GitHub Desktop.
Save kiennt/4967466 to your computer and use it in GitHub Desktop.
Pre define method for array sort
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
Copy link

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