Dynamic method calling in Ruby

后端 未结 5 762

As far as I am aware there are three ways to dynamically call a method in Ruby:

Method 1:

s = SomeObject.new
method = s.method(:dynamic_method)
metho         


        
5条回答
  •  悲哀的现实
    2020-12-12 20:06

    I updated the benchmark from @Stefan to check if there are some speed improvements when saving reference to method. But again – send is much faster than call

    require 'benchmark'
    
    class Foo
      def bar; end
    end
    
    foo = Foo.new
    foo_bar = foo.method(:bar)
    
    Benchmark.bm(4) do |b|
      b.report("send") { 1_000_000.times { foo.send(:bar) } }
      b.report("call") { 1_000_000.times { foo_bar.call } }
    end
    

    These are the results:

               user     system      total        real
    send   0.080000   0.000000   0.080000 (  0.088685)
    call   0.110000   0.000000   0.110000 (  0.108249)
    

    So send seems to be the one to take.

提交回复
热议问题