&method(:method_name) 习语对 Ruby 的性能不利吗? [英] Is the &method(:method_name) idiom bad for performance in Ruby?

查看:47
本文介绍了&method(:method_name) 习语对 Ruby 的性能不利吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了 &method(:method_name) 语法.(这使用 Object#method 方法 - RDoc 链接) 例如,

I've recently come across the &method(:method_name) syntax. (This uses the Object#method method - RDoc link) For example,

[5, 7, 8, 1].each(&method(:puts))

相当于

[5, 7, 8, 1].each{|number| puts number}

在 Ruby 的各种实现中,与前者相比,后者是否存在性能损失?如果是这样,实施者是否正在努力提高其性能?

Are there performance penalties for the latter compared to the former in the various implementations of Ruby? If so, are the implementors working on improving its performance?

推荐答案

是的,它似乎对性能不利.

Yes, it appears to be bad for performance.

def time
  start = Time.now
  yield
  "%.6f" % (Time.now - start)
end

def do_nothing(arg)
end


RUBY_VERSION # => "1.9.2"

# small
ary = *1..10
time { ary.each(&method(:do_nothing)) }     # => "0.000019"
time { ary.each { |arg| do_nothing arg } }  # => "0.000003"


# large
ary = *1..10_000
time { ary.each(&method(:do_nothing)) }     # => "0.002787"
time { ary.each { |arg| do_nothing arg } }  # => "0.001810"


# huge
ary = *1..10_000_000
time { ary.each(&method(:do_nothing)) }     # => "37.901283"
time { ary.each { |arg| do_nothing arg } }  # => "1.754063"

这似乎是在 JRuby 中解决的:

It looks like this is addressed in JRuby:

$ rvm use jruby
Using /Users/joshuajcheek/.rvm/gems/jruby-1.6.3

$ xmpfilter f.rb 
def time
  start = Time.now
  yield
  "%.6f" % (Time.now - start)
end

def do_nothing(arg)
end


RUBY_VERSION # => "1.8.7"

# small
ary = *1..10
time { ary.each(&method(:do_nothing)) }     # => "0.009000"
time { ary.each { |arg| do_nothing arg } }  # => "0.001000"


# large
ary = *1..10_000
time { ary.each(&method(:do_nothing)) }     # => "0.043000"
time { ary.each { |arg| do_nothing arg } }  # => "0.055000"


# huge
ary = *1..10_000_000
time { ary.each(&method(:do_nothing)) }     # => "0.427000"
time { ary.each { |arg| do_nothing arg } }  # => "0.634000"

这篇关于&method(:method_name) 习语对 Ruby 的性能不利吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆