4 ms·
The Ruby program takes more time because it is not optimised and it also checks for numeric overflow. The following Ruby program puts (1 .. 21).inject :*
by wedesoft 15y ago
The Ruby program takes more time because it is not optimised and it also checks for numeric overflow. The following Ruby program
puts (1 .. 21).inject :*
will output "51090942171709440000". And
puts (1 .. 21).inject(:*).class
will output "Bignum" because Ruby switches to big numbers when its integer representation is exceeded.
- ssmoot 15y agoYou make a valid point, but I think it's missing the forest. The example I posted actually results in a Fixnum. It's addition, not multiplication. Simple math operations are an admittedly terrible way to demonstrate the point I was trying to make (method dispatch and object instantiation overhead). Dismiss it, accept it, or dig deeper verify it. :-)