Mike Austin's Blog

Sunday, March 12, 2006

Many solutions, different efficiencies

I compared 3 ways of creating even-squares of numbers in Ruby, and the fastests seems to be 'map {} .compact!'. Here are the methods, each performed 1,000,000 times:
1: (1..10).inject( Array.new )
{ |a, i| a << i * i if i % 2 == 0; a }
2: (1..10).select { |i| i % 2 == 0 }.collect { |i| i * i }
3: (1..10).map { |i| i * i if i % 2 == 0 }.compact!
and here are the results:
         user     system      total        real
1: 31.734000 0.015000 31.749000 ( 31.956000)
2: 22.313000 0.000000 22.313000 ( 22.416000)
3: 19.890000 0.000000 19.890000 ( 19.976000)
The first one is probably the most memory efficient, while the last is probably the least memory efficient. Fast, Cheap, Good - pick *two* ;)