Skip to content

Instantly share code, notes, and snippets.

@wils3005
Created March 16, 2019 23:00
Show Gist options
  • Save wils3005/529378e12cdff3432b663e1b920b8239 to your computer and use it in GitHub Desktop.
Save wils3005/529378e12cdff3432b663e1b920b8239 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'benchmark/ips'
Arr = Array.new(1000) { rand }.freeze
class MyClass
def self.call(arg)
new(arg).call
end
def self.foo
@foo ||= ->(arg) { new(arg).call }
end
def self.bar
@bar ||= method(:call).to_proc
end
attr_reader :arg
def initialize(arg)
@arg = arg
end
def call
Float(arg)**2
end
end
Benchmark.ips do |benchmark|
benchmark.config(time: 10, warmup: 4)
benchmark.report('lambda') { Arr.each(&MyClass.foo) }
benchmark.report('method to lambda') { Arr.each(&MyClass.bar) }
benchmark.compare!
end
# Warming up --------------------------------------
# lambda 300.000 i/100ms
# method to lambda 290.000 i/100ms
# Calculating -------------------------------------
# lambda 3.125k (± 2.5%) i/s - 31.500k in 10.086087s
# method to lambda 2.886k (± 5.2%) i/s - 29.000k in 10.087187s
# Comparison:
# lambda: 3125.1 i/s
# method to lambda: 2885.6 i/s - 1.08x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment