Why is array.min so slow?

It's even faster if you use:

def my_min(ary)
  the_min = ary[0]
  i = 1
  len = ary.length
  while i < len
    the_min = ary[i] if ary[i] < the_min
    i += 1
  end
  the_min
end

NOTE

I know this is not an answer, but I thought it was worth sharing and putting this code into a comment would have been exceedingly ugly.


Have a look at the implementation of Enumerable#min. It might use each eventually to loop through the elements and get the min element, but before that it does some extra checking to see if it needs to return more than one element, or if it needs to compare the elements via a passed block. In your case the elements will get to be compared via min_i function, and I suspect that's where the speed difference comes from - that function will be slower than simply comparing two numbers.

There's no extra optimization for arrays, all enumerables are traversed the same way.