gpt4 book ai didi

ruby - Ruby 2 中的惰性求值

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:38 24 4
gpt4 key购买 nike

我最近安装了 Ruby 2.0.0,发现它现在有一个 lazy Enumerable mixin 的方法。根据之前使用函数式语言的经验,我知道这有助于提高代码效率。

我做了一个懒惰与渴望的基准测试(不确定它是否有实际意义),发现懒惰总是更快。为什么是这样?是什么让惰性求值更适合大输入?

基准代码:

#!/usr/bin/env ruby

require 'benchmark'

num = 1000
arr = (1..50000).to_a

Benchmark.bm do |rep|
rep.report('lazy') { num.times do ; arr.lazy.map { |x| x * 2 }; end }
rep.report('eager') { num.times do ; arr.map { |x| x * 2}; end }
end

基准报告样本:

       user     system      total        real
lazy 0.000000 0.000000 0.000000 ( 0.009502)
eager 5.550000 0.480000 6.030000 ( 6.231269)

最佳答案

它太懒了,甚至不做任何工作——可能是因为您实际上并没有使用操作的结果。将 sleep() 放入其中以确认:

> Benchmark.bm do |rep|
rep.report('lazy') { num.times do ; arr.lazy.map { |x| sleep(5) }; end }
rep.report('notlazy') { 1.times do ; [0,1].map { |x| sleep(5) } ; end }
end

user system total real
lazy 0.010000 0.000000 0.010000 ( 0.007130)
notlazy 0.000000 0.000000 0.000000 ( 10.001788)

关于ruby - Ruby 2 中的惰性求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16972184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com