I was solving a problem that asked me to find the sum of all EVEN fibonacci numbers under 4,000,000 and I noticed that the below CoffeeScript executed faster than the below Ruby.
CoffeeScript
sum = 0
f = (n) ->
if n == 0 then return 0
else if n == 1 then return 1
else return f(n-1) + f(n-2)
console.log "Starting..."
for i in [1..4000000]
ff = f(i)
break if ff >= 4000000
sum += ff if ff % 2 == 0
console.log ".." + ff
console.log "Sum:" + sum
Ruby
sum = 0
def F(n)
if n.eql? 0
return 0
elsif n.eql? 1
return 1
else
return F(n-1) + F(n-2)
end
end
puts "Starting..."
4000000.times do |num|
the_num = F(num)
break if the_num >= 4000000
sum += the_num if the_num % 2 == 0
puts ".." + the_num.to_s
end
puts "Sum:" + sum.to_s
It took nearly 6-8 seconds for the Ruby script to find all even fibonacci numbers under 4,000,000 while it took roughly 0.2 seconds to complete for the NodeJS execution of the transpilation of coffeescript. Why is this??
$ ruby --version
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin12.0]
$ node --version
v0.10.25