Ruby – 在众多方法中,哪一种实现效率最高?

更新于
2026-10-09 19:21:24
2阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计265个文字,预计阅读时间需要2分钟。

Ruby – 在众多方法中,哪一种实现效率最高?

若想从0到5打印x,并计算x的绝对值加上p和x的乘积,可以使用以下代码:

rubyx=0p=1

6.times do puts x: #{x}, |x| + p * x: #{x.abs + p * x}end

0.upto(5) do |x| puts x: #{x}, |x| + p * x: #{x.abs + p * x}end

x=0for x in 0..5 puts x: #{x}, |x| + p * x: #{x.abs + p * x}end

如果我想从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是一个更好的工具.

Ruby – 在众多方法中,哪一种实现效率最高?

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时间可能会使循环迭代次数相形见绌.结果,它足够接近无所谓.

本文共计265个文字,预计阅读时间需要2分钟。

Ruby – 在众多方法中,哪一种实现效率最高?

若想从0到5打印x,并计算x的绝对值加上p和x的乘积,可以使用以下代码:

rubyx=0p=1

6.times do puts x: #{x}, |x| + p * x: #{x.abs + p * x}end

0.upto(5) do |x| puts x: #{x}, |x| + p * x: #{x.abs + p * x}end

x=0for x in 0..5 puts x: #{x}, |x| + p * x: #{x.abs + p * x}end

如果我想从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是一个更好的工具.

Ruby – 在众多方法中,哪一种实现效率最高?

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时间可能会使循环迭代次数相形见绌.结果,它足够接近无所谓.