Skip to content

Instantly share code, notes, and snippets.

@bensheldon
Created May 12, 2025 18:47
Show Gist options
  • Save bensheldon/d33e424d01c31d041653daddd0c9e989 to your computer and use it in GitHub Desktop.
Save bensheldon/d33e424d01c31d041653daddd0c9e989 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
# Inline Gemfile for dependencies
gemfile(true) do
source "https://rubygems.org"
gem "benchmark-ips"
end
class MyClass
NUMBERS = [1, 2, 3, 4, 5].freeze
def as_block
NUMBERS.map do |number|
some_method(number)
end
end
def as_bound_method
NUMBERS.map(&method(:some_method))
end
def some_method(number)
"Hello, World! #{number}"
end
end
require "benchmark/ips"
instance = MyClass.new
Benchmark.ips do |x|
x.report("as_block") { instance.as_block }
x.report("as_bound_method") { instance.as_bound_method }
x.compare!
end
@bensheldon
Copy link
Author

❯ ruby benchmark_bound_method.rb
Fetching gem metadata from https://rubygems.org/.
Resolving dependencies...
Fetching benchmark-ips 2.14.0
Installing benchmark-ips 2.14.0
ruby 3.4.3 (2025-04-14 revision d0b7e5b6a0) +PRISM [arm64-darwin24]
Warming up --------------------------------------
            as_block   181.909k i/100ms
     as_bound_method   116.695k i/100ms
Calculating -------------------------------------
            as_block      1.879M (± 1.4%) i/s  (532.09 ns/i) -      9.459M in   5.034090s
     as_bound_method      1.137M (± 3.6%) i/s  (879.50 ns/i) -      5.718M in   5.035501s

Comparison:
            as_block:  1879392.9 i/s
     as_bound_method:  1137010.6 i/s - 1.65x  slower

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