Skip to content

Instantly share code, notes, and snippets.

@AJFaraday
Last active December 5, 2016 16:37
Show Gist options
  • Save AJFaraday/4341d97a534f3f13a4d712cc3e487b17 to your computer and use it in GitHub Desktop.
Save AJFaraday/4341d97a534f3f13a4d712cc3e487b17 to your computer and use it in GitHub Desktop.
Which one is more efficient?
require 'benchmark'
puts Benchmark.measure do
1000.times{method1(array)}
end
# ...
# 0.020000 0.010000 0.030000 ( 0.027314)
puts Benchmark.measure do
1000.times{method2(array)}
end
# ...
# 0.010000 0.010000 0.020000 ( 0.026339)
array = ['banana', 'cat', 'pineapple', 'egg', 'fridge', 'smudge', 'panda']
# More efficient?
def method1(array)
array.reject{|thing| thing.include?('a')}.each do |thing|
puts thing.reverse
end
end
# Or is this better?
def method2(array)
array.each do |thing|
next if thing.include?('a')
puts thing.reverse
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment