[MacRuby-devel] Speed

Uliano Guerrini uliano.guerrini at gmail.com
Sun Nov 22 01:25:21 PST 2009


I'm new to Ruby BECAUSE of MacRuby

While learning I run this simple exercise (the sum of even fibonacci less than 4 million) on both MacRuby 0.5.2 and ruby 1.9.1.

the recursive version runs about 5 times faster on MacRuby and that was expected but the iterative runs about 1000!!! times slower, and that is *frankly* unacceptable.

What's going on?

uliano

def fib_rec(n)
  n < 2 ? n : fib_rec(n-1) + fib_rec(n-2)
end


def fib_iter(limit)
  yield 0
  yield 1
  lastbut=0
  last=1
  while true
    a=lastbut+last
    if a<=limit 
      yield a
    else
      return
    end      
    lastbut=last
    last=a
  end
end


sum=0
i=0
start=Time.now
while (f=fib_rec(i))<=4_000_000
  sum += f if f%2==0
  i+=1
end
time=Time.now-start

puts 'recursive'
puts 'sum = ',sum
puts 'time = ',time

sum=0
start=Time.now
fib_iter(4_000_000) { |f| sum+=f if f%2==0}
time=Time.now-start

puts 'iterative'
puts 'sum = ',sum
puts 'time = ',time



More information about the MacRuby-devel mailing list