Speeding up Ruby with Lua

written by amcvega on November 4th, 2007 @ 12:00 AM

Everyone knows ruby is slow. That’s why I find that the ruby community is more obsessed with optimization than any other. One of the solutions tossed around to improve the performance of ruby programs is to forgo ruby in the complex computations and switch to C.

I don’t doubt this will work. In fact, based on all the stuff I’ve read, this is really a great way to speed up your app while still using the wonder (and joy) that is ruby. However I am loathe to go back to C. I mean, the whole reason I moved to ruby was because I wanted to use a high-level language and all the cool concepts not available to lower level languages.

Enter Lua. I’ve been reading about Lua for a while now. I know it’s fast ; it’s used in WoW and a whole lot of other stuff. It’s also a high level language which I find has a lot in common with lisp (something I’ve always wanted to learn). It’s also designed to be embedded into applications; much the same way ruby was initially designed as a tool for admins. It got me thinking that maybe Lua can help me speed up Ruby.

I found a nifty little library that allows lua to be called from within ruby called rubyluabridge. I installed it on my machine and decided to run the classic fibonacci benchmark test.


fib.rb t = Time.now def fib(n) if n == 1 or n == 2 return 1 else return fib(n-1) + fib(n-2) end end answer = fib(ARGV[0].to_i) puts "Answer: #{answer}" puts "Calculation Time: #{Time.now - t}" new_fib.rb t = Time.now require 'rubyluabridge' l = Lua::State.new l.eval <<-LUA_END function fib(n) if n == 1 or n == 2 then return 1 else return fib(n-1) + fib(n-2) end end LUA_END l.eval "answer = fib(#{ARGV[0]})" puts "Answer: #{l.answer.to_i}" puts "Calculation Time: #{Time.now - t}"

Here are the results:

fib.rb 20
Answer: 6765
Calculation Time: 0.071339
new_fib.rb 20
Answer: 6765
Calculation Time: 0.034658
fib.rb 33
Answer: 3524578
Calculation Time: 11.272733
new_fib.rb 33
Answer: 3524578
Calculation Time: 2.103146


There is definitely an improvement in the processing time of the app with lua embedded. This is more apparent the more complex the calculation.

But the most striking thing is that there is very little change in the syntax of the code. If you’ll look at the embedded lua function fib(), it is almost identical to the ruby original. We got all that speed (around 500% in this example) for code that is essentially similar. I find it looks a lot better then lisp. (parentheses anyone?)

So there you have it, embedding lua into ruby for a quick performance boost.

Post a comment