Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Lazy chining
require 'benchmark'
require 'benchmark/ips'
NORMAL_ITERATIONS = 100
LONG_ITERATIONS = 2000
def map_to_self(array, iterations)
iterations.times do
array = array.map{ |i| i }
end
array
end
Benchmark.ips do |x|
x.report('[n] iterative') {
map_to_self([1], NORMAL_ITERATIONS).to_a
}
x.report('[n] lazy preparation') {
map_to_self([1].lazy, NORMAL_ITERATIONS)
}
x.report('[n] lazy evaluation') {
map_to_self([1].lazy, NORMAL_ITERATIONS).to_a
}
x.report('[l] iterative') {
map_to_self([1], LONG_ITERATIONS).to_a
}
end
lazy_long_map = map_to_self([1].lazy, LONG_ITERATIONS)
begin
lazy_long_map.to_a
rescue SystemStackError
puts 'Lazy chaining is recursive o_O'
end
Calculating -------------------------------------
[n] iterative 6.764k i/100ms
[n] lazy preparation 380.000 i/100ms
[n] lazy evaluation 224.000 i/100ms
[l] iterative 340.000 i/100ms
-------------------------------------------------
[n] iterative 69.078k (± 2.3%) i/s - 351.728k
[n] lazy preparation 3.760k (± 4.6%) i/s - 19.000k
[n] lazy evaluation 2.267k (± 2.0%) i/s - 11.424k
[l] iterative 3.717k (± 1.5%) i/s - 18.700k
Lazy chaining is recursive o_O
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.