squ*_*guy 2 ruby lazy-evaluation
我最近安装了Ruby 2.0.0,发现它现在有一个懒惰的方法用于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
Run Code Online (Sandbox Code Playgroud)
基准报告样本:
user system total real
lazy 0.000000 0.000000 0.000000 ( 0.009502)
eager 5.550000 0.480000 6.030000 ( 6.231269)
Run Code Online (Sandbox Code Playgroud)
它太懒了,甚至没有做好工作 - 可能是因为你实际上没有使用操作的结果.放在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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
480 次 |
| 最近记录: |