Last active
October 21, 2022 21:03
-
-
Save leonid-shevtsov/cea7c6181370b0c48f73888a03dc00cd 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' | |
def sum(x, y) | |
x + y | |
end | |
def nested_sum(x, y) | |
sum(x, y) | |
end | |
def nested_twice_sum(x, y) | |
nested_sum(x, y) | |
end | |
ary = (1..100).to_a | |
sum_ref = method :sum | |
sum_proc = proc { |x, y| x + y } | |
class Foo | |
def sum(x, y) | |
x + y | |
end | |
define_method :sum_meta do |x, y| | |
x + y | |
end | |
end | |
Foo.class_eval do | |
def sum_eval(x, y) | |
x + y | |
end | |
end | |
foo = Foo.new | |
Benchmark.ips do |x| | |
x.report('direct') { ary.reduce { |acc, x| acc + x } } | |
x.report('fn') { ary.reduce { |acc, x| sum(acc, x) } } | |
x.report('method') { ary.reduce { |acc, x| sum_ref.call(acc, x) } } | |
x.report('proc') { ary.reduce { |acc, x| sum_proc.call(acc, x) } } | |
x.report('member fn') { ary.reduce { |acc, x| foo.sum(acc, x) } } | |
x.report('member meta fn') { ary.reduce { |acc, x| foo.sum_meta(acc, x) } } | |
x.report('member eval fn') { ary.reduce { |acc, x| foo.sum_eval(acc, x) } } | |
x.report('nested fn') { ary.reduce { |acc, x| nested_sum(acc, x) } } | |
x.report('nested twice fn') { ary.reduce { |acc, x| nested_twice_sum(acc, x) } } | |
x.report('send') { ary.reduce { |acc, x| foo.send(:sum, acc, x) } } | |
x.compare! | |
end |
Author
leonid-shevtsov
commented
Oct 21, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment