Created
November 13, 2020 17:22
-
-
Save serradura/e226f80560f20579b01809b53b41f97c to your computer and use it in GitHub Desktop.
Ruby lambda benchmark
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 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'benchmark-ips' | |
end | |
Benchmark.ips do |x| | |
x.config(time: 5, warmup: 2) | |
CopyStrWithClosure = -> str { -> n { str * n } } | |
module CopyStrByNumbers | |
def self.call(numbers, str) | |
numbers.map { |n| copy(str, n) } | |
end | |
def self.copy(str, n); str * n; end | |
end | |
class StrCopier | |
def initialize(str) | |
@str = str | |
end | |
def call(numbers) | |
numbers.map { |n| copy(@str, n) } | |
end | |
private def copy(str, n); str * n; end | |
end | |
STR = 'Ho! ' | |
NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
str_copier = StrCopier.new(STR) | |
copy_with_closure = CopyStrWithClosure[STR] | |
x.report("inline block") { NUMBERS.map { |n| STR * n } } | |
x.report("static method") { CopyStrByNumbers.call(NUMBERS, STR) } | |
x.report("instance method") { str_copier.call(NUMBERS) } | |
x.report("lambda + closure") { NUMBERS.map(©_with_closure) } | |
x.compare! | |
end | |
Warming up -------------------------------------- | |
# inline block 28.452k i/100ms | |
# static method 29.079k i/100ms | |
# instance method 28.733k i/100ms | |
# lambda + closure 32.472k i/100ms | |
# Calculating ------------------------------------- | |
# inline block 315.701k (± 3.3%) i/s - 1.593M in 5.052599s | |
# static method 288.457k (± 3.9%) i/s - 1.454M in 5.048551s | |
# instance method 290.406k (± 3.0%) i/s - 1.465M in 5.050690s | |
# lambda + closure 317.376k (± 4.8%) i/s - 1.591M in 5.025673s | |
# Comparison: | |
# lambda + closure: 317376.1 i/s | |
# inline block: 315701.3 i/s - same-ish: difference falls within error | |
# instance method: 290406.4 i/s - 1.09x (± 0.00) slower | |
# static method: 288457.2 i/s - 1.10x (± 0.00) slower | |
# [Done] exited with code=0 in 28.416 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment