Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Last active October 21, 2022 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonid-shevtsov/cea7c6181370b0c48f73888a03dc00cd to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/cea7c6181370b0c48f73888a03dc00cd to your computer and use it in GitHub Desktop.
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
@leonid-shevtsov
Copy link
Author

leonid-shevtsov commented Oct 21, 2022

Comparison:
              direct:   328078.4 i/s
                  fn:   235690.2 i/s - 1.39x  (± 0.00) slower
      member eval fn:   231263.3 i/s - 1.42x  (± 0.00) slower
           member fn:   228173.9 i/s - 1.44x  (± 0.00) slower
                proc:   185414.4 i/s - 1.77x  (± 0.00) slower
           nested fn:   167240.5 i/s - 1.96x  (± 0.00) slower
      member meta fn:   153972.7 i/s - 2.13x  (± 0.00) slower
                send:   147509.1 i/s - 2.22x  (± 0.00) slower
              method:   136942.0 i/s - 2.40x  (± 0.00) slower
     nested twice fn:   131791.0 i/s - 2.49x  (± 0.00) slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment