Ruby: Proc#call vs yield

后端 未结 6 1458
野性不改
野性不改 2020-12-02 05:54

What are the behavioural differences between the following two implementations in Ruby of the thrice method?

module WithYield
  def self.thrice
         


        
6条回答
  •  有刺的猬
    2020-12-02 06:36

    Here's an update for Ruby 2.x

    ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]

    I got sick of writing benchmarks manually so I created a little runner module called benchable

    require 'benchable' # https://gist.github.com/naomik/6012505
    
    class YieldCallProc
      include Benchable
    
      def initialize
        @count = 10000000    
      end
    
      def bench_yield
        @count.times { yield }
      end
    
      def bench_call &block
        @count.times { block.call }
      end
    
      def bench_proc &block
        @count.times &block
      end
    
    end
    
    YieldCallProc.new.benchmark
    

    Output

                          user     system      total        real
    bench_yield       0.930000   0.000000   0.930000 (  0.928682)
    bench_call        1.650000   0.000000   1.650000 (  1.652934)
    bench_proc        0.570000   0.010000   0.580000 (  0.578605)
    

    I think the most surprising thing here is that bench_yield is slower than bench_proc. I wish I had a little more of an understanding for why this is happening.

提交回复
热议问题