Skip to content

Instantly share code, notes, and snippets.

@mrkn
Last active February 14, 2018 15:24
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 mrkn/26a0fcfc431a45fe809fbbef95aceaf5 to your computer and use it in GitHub Desktop.
Save mrkn/26a0fcfc431a45fe809fbbef95aceaf5 to your computer and use it in GitHub Desktop.
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