Skip to content

Instantly share code, notes, and snippets.

@mrkn mrkn/same_all_bench.rb
Last active Feb 14, 2018

Embed
What would you like to do?
require 'benchmark'
LEN = 10000
TRY = 1000
s0 = 'x' * 100
s1 = 'x' * 99 + 'y'
cases = {
shuffle: Array.new(LEN) {|i| i }.shuffle,
tail0: [*Array.new(LEN - 1) { s0.dup }, s1],
head0: [s1, *Array.new(LEN - 1) { s0.dup }],
all1: Array.new(LEN) { s0.dup }
}
class Integer
def foo
self * self
end
end
class String
alias foo upcase
end
cases.each do |name, ary|
puts "-" * 40
puts "Benchmark case: #{name}"
Benchmark.bm(10) do |x|
x.report('all?-method-1') do
TRY.times { ary.all? {|e| e.foo == ary[0].foo } }
end
x.report('all?-method-2') do
TRY.times { ary.empty? || ary[0].foo.yield_self {|e0| ary.all? {|e| e.foo == e0 } } }
end
x.report('all?-method-3') do
TRY.times { ary.empty? || ary[0].foo.yield_self {|e0| ary[1..-1].all? {|e| e.foo == e0 } } }
end
x.report('all?-item') do
TRY.times { ary.all? {|e| e == ary[0] } }
end
x.report('opt-method') do
TRY.times { ary.empty? || ary.map {|e| e.foo }.yield_self {|a| a[0..-2] == a[1..-1] } }
end
x.report('opt-item') do
TRY.times { ary.empty? || ary[0..-2] == ary[1..-1] }
end
end
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.