I'm trying to process a large list of numbers:
require 'benchmark'
N = 999999
Benchmark.bm 10 do |bm|
bm.report 'Eager:' do
(0..N).select(&:even?).map{|x| x * x}.reduce(&:+)
end
bm.report 'Lazy:' do
(0..N).lazy.select(&:even?).map{|x| x * x}.reduce(&:+)
end
end;
To my understanding, the lazy version should be much faster, because the eager version needs to allocate two lists of half a million items each(one for select
and one for map
) while the lazy version is streaming everything.
However, when I run it, the lazy version takes more than twice as long as the eager one! (http://rextester.com/OTEX7399)
user system total real
Eager: 0.210000 0.010000 0.220000 ( 0.216572)
Lazy: 0.580000 0.000000 0.580000 ( 0.635091)
How can it be?