Skip to content

Instantly share code, notes, and snippets.

@thorvn
Created August 21, 2018 04:48
Show Gist options
  • Save thorvn/f63e89ffa3c8e9af11865e428bb7fa40 to your computer and use it in GitHub Desktop.
Save thorvn/f63e89ffa3c8e9af11865e428bb7fa40 to your computer and use it in GitHub Desktop.
Benchmark ruby
sizes = [10, 50, 100, 1000]
sizes.each do |size|
array = size.times.map { |i| rand(size) }
threshold = size / 2
Benchmark.bmbm(2) do |x|
x.report("select #{size}") do
array.select { |item| item > threshold }
.each { |item| item * item }
end
x.report("if #{size}") do
array.each do |item|
item * item if item > threshold
end
end
x.report("next #{size}") do
array.each do |item|
next unless item > threshold
item * item
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment