【问题标题】:Is a nested yield or conversion to block faster?嵌套收益或转换是否更快?
【发布时间】:2012-09-03 03:39:18
【问题描述】:

在 Ruby 中,经常说yield 比将块转换为Proc 更快。

例如:

def method
  yield
end

def method &block
  block.call
end

但是,如果需要将一个块作为参数传递几层,该怎么办?无论您传递多少层,yield 总是更快吗?是取决于多少层,还是取决于每个闭包中的变量数?

我问的原因是因为yield 几层深涉及多次将其包装成一个块,而将其转换为Proc 可能只需执行一次即可节省时间。我也想知道是否取决于to_proc方法中需要打包多少变量。

这样更快:

嵌套收益率?

def method1;method2 {yield};end
def method2;method3 {yield};end
  ...
def methodn;yield;end

还是&block

def method1 █method2 █end
def method2 █method3 █end
  ...
def methodn █block.call;end

【问题讨论】:

标签: ruby yield


【解决方案1】:
require "benchmark"

def test_yield
    yield
end

def test_block(&block)
    block.call
end

Benchmark.bm do |b|

    b.report("test_yield") {
        10000.times{ test_yield {1+1} }
    }

    b.report("test_block") {
        10000.times{ test_block {1+1} }
    }

end



      user     system      total        real
test_yield  0.000000   0.000000   0.000000 (  0.002623)
test_block  0.000000   0.000000   0.000000 (  0.009497)

看起来 Yield 比 block.call 更快。不过我很想知道为什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2020-07-22
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多