加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 以下哪项是最有效的

发布时间:2020-12-17 01:34:58 所属栏目:百科 来源:网络整理
导读:如果我想从0到5打印x 6.times {|x| p x}(0..5).each {|x| p x}0.upto(5) {|x| p x}for x in 0..5 p xend 解决方法 benchmark/ips是一个更好的工具. require 'benchmark/ips'Benchmark.ips do |x| x.report("times") { 6.times {|x| } } x.report("range iter
如果我想从0到5打印x

6.times {|x| p x}

(0..5).each {|x| p x}

0.upto(5) {|x| p x}

for x in 0..5
  p x
end

解决方法

benchmark/ips是一个更好的工具.

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("times") { 6.times {|x| } }
  x.report("range iteration") { (0..5).each {|x| } }
  x.report("upto") { 0.upto(5) {|x| } }
  x.report("for") do
    for x in 0..5
    end
  end
end

Ruby 2.2.0上的结果:

Calculating -------------------------------------
               times    88.567k i/100ms
     range iteration    88.519k i/100ms
                upto    86.749k i/100ms
                 for    84.118k i/100ms
-------------------------------------------------
               times      2.093M (± 0.2%) i/s -     10.451M
     range iteration      2.053M (± 0.4%) i/s -     10.268M
                upto      2.103M (± 0.2%) i/s -     10.583M
                 for      1.949M (± 0.2%) i/s -      9.758M

在这里循环一个空体是更好的主意,因为从p开始的IO时间可能会使循环迭代次数相形见绌.结果,它足够接近无所谓.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读