Skip to content

Instantly share code, notes, and snippets.

@fbernier
Last active August 29, 2015 13:56
Show Gist options
  • Save fbernier/9231807 to your computer and use it in GitHub Desktop.
Save fbernier/9231807 to your computer and use it in GitHub Desktop.
Enumerator#lazy benchmarking
# Enumerator#lazy is very slow and should only be used when iterating over large/infinite collections
# where you know you are going to get your results quite early in the iteration.
# This benchmark is purposely made to advantage the lazy version, without much success.
require 'benchmark/ips'
class Enumerator::Lazy
def filter_map
Lazy.new(self) do |yielder, *values|
result = yield *values
yielder << result if result
end
end
end
Benchmark.ips do |r|
r.report("map+compact") do
(0..50).map{|a| 'lol' if a.even?}.compact.first(5)
end
r.report("filter_map") do
(0..50).lazy.filter_map{|a| 'lol' if a.even?}.first(5)
end
end
Calculating -------------------------------------
map+compact 12035 i/100ms
filter_map 10588 i/100ms
-------------------------------------------------
map+compact 135411.8 (±0.9%) i/s - 685995 in 5.066383s
filter_map 114386.4 (±4.9%) i/s - 571752 in 5.010041s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment