El Martes, 12 de Enero de 2010, R. Kumar escribió:
> If i use something like:
> >    array.count rescue array.size
> 
> does the rescue set up anything internally that will make this
> inefficient ?
> 
> I have other options too, however, i want to minimize code clutter since
> this situation is rare (my app says it works under 1.8.7 and 1.9).
> Someones using it in 1.8.6 which i learn has no array#count. Otoh, 1.9
> has no array#size.

Ruby 1.9 has Array#size, sure.


> Other options are :
> 
> unless Array.method_defined?(:count) then
>   class Array
>     def count
>       size
>     end
>   end
> end
> # remark: i assume this is a one time startup cost
> 
> 
> or:
> 
> if array.respond_to?(:count) then
>   array.count
> else
>   array.size
> end
> # remark: evaluated each time, so cost is high
> 
> My hope is that the rescue clause of the first example is only looked at
> by the interpreter if an error occurs, otherwise there's no penalty for
> it.
> Suggestions ?

Forgetting the fact tha Array#size does exist iunder 1.9, I think that 
defining the method "count" (in case it doesn't exist) is a bit faster:

Ruby allows redefining methods in runtime which means that when a method is 
invoked the interpreter must look for it and execute its code. Then:

  array.count rescue array.size

- First it involves looking for "count" method.
- It doesn't exist so raises.
- Then "size" is invoked so it involves looking for "size" method.


  unless Array.method_defined?(:count) then
    class Array
      def count
        size
      end
    end
  end

In this case:
- First "count" is looked for.
- It's found and "size" is invoked so "size" method is looked for.

It's faster as you avoid the rescue.





-- 
Iñaki Baz Castillo <ibc / aliax.net>