Home > Net >  why ruby upto method is so slow?
why ruby upto method is so slow?

Time:11-15

n = 5000000
Benchmark.bm(7) do |x|
  x.report("upto  :")   { for i in 1..n; 0.upto(( 10 )) ; end }
  x.report("range :")   { for i in 1..n; 0..10 ; end }
end

Results:

              user     system      total        real
upto   :     1.116440   0.068953   1.185393 (  1.187705)
range  :     0.156921   0.000000   0.156921 (  0.156759)

Why does upto() takes so much time compared to the manual range ?

CodePudding user response:

This benchmark actually compares oranges to apples now: upto performs the actual iterations under the hood, while 0..10 is a range literal that causes only a creation of a tiny object per iteration (with no memory allocations).

  •  Tags:  
  • ruby
  • Related