My thoughts have started to lean back toward compilation again, so I thought I'd go through a little exercise and mock up what a fib() method might look like compiled. Given the following definition of fib:

def fib(n)
  if n<2
    n
  else
    fib(n-2)+fib(n-1)
  end
end

I came up with the following Java/JRuby code:

    public static IRubyObject fib2(IRubyObject recv, IRubyObject n) {
        IRuby runtime = recv.getRuntime();
        RubyFixnum two = runtime.newFixnum(2);
        RubyFixnum >        if (n.callMethod("<", two).isTrue()) {
          return n;
        } else {
          return fib2(recv, n.callMethod("-", two)).callMethod("+", fib2(recv, n.callMethod("-",one)));
        }
    }


Not too complicated, really. This avoids a whole chunk of interpretation. It isn't green-threadable and I'm sure there's bits that are missing...here's a short list off the top of my head:

- thread-event checks in appropriate places
- tracing calls
- the recursive calls to fib should really be dynamic dispatched as well

I'm sure there's more, but this is good for comparison. I also made a pure Java version for comparison:

    public static int fib_internal(int n) {
        if (n < 2) {
            return n;
        } else {
            return fib_internal(n - 2) + fib_internal(n - 1);
        }
    }

So the next obvious step was to benchmark all these and compare them. I ran fib(30) with all three and in Ruby as well just to see.

Pure ruby in JRuby: 25.7s
"Compiled" in JRuby: 8.8s
Pure ruby in Ruby: 2.0s
Pure Java: 0.014s

There's a bit we can learn from this.

- Interpretation (and the missing bits above) account for a large part of our overhead, as we know. Here, it's roughly 2/3.
- However, even when interpretation is removed from the equation, we're still over four times slower than Ruby. That's not good.
- Ruby isn't even that fast at this in the grand scheme of things. Two seconds to do fib(30)?
- Man, Java is f'n fast. In this case it's probably because iJava has primitives.

So I think there's a lot we can do before compilation to speed things up considering how slow we still are running this rough compiled version of fib. We need to reduce the impact of the interpreter as well in the short term.

Comments?

--
Charles Oliver Nutter @ headius.blogspot.com
JRuby Developer @ www.jruby.org
Application Architect @ www.ventera.com
-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
Jruby-devel mailing list
Jruby-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/jruby-devel

Reply via email to