views:

79

answers:

1

An algorithm written in Java should be faster than the same algorithm written in JRuby, right?.

However, if I write the algorithm in Java and then call it from JRuby, will I still get the performance advantages of java?

I ask this because I am writing a very complicated utility class for my JRuby on Rails app and need to choose whether to do it in Java or JRuby.

So, if I use the following code:

class UtilitySampleWrapper
  include Java
  require 'utility.jar' #could also use .js class files if that makes a difference

  def initialize
    @p = Utility.new #this is the java utility class
  end

end

Will any code run in the @p object of Utility class be run in pure java and have all of the speed advantages that implies?

if I call

@p.iterate(50)

will the iterate function of the Utility class run in pure Java and then return its result to my JRuby code?

Thanks!

+2  A: 

An algorithm written in Java should be faster than the same algorithm written in JRuby, right?.

It depends on how well you write the Java version. It is also theoretically possible that for certain algorithms the JRuby compiler can emit bytecodes that run faster than the Java compiler would emit for a functionally equivalent Java program.

But generally I would expect a hand-optimized Java algorithm to run faster than a hand-optimized JRuby algorithm because of:

  • relative maturity of the Java and JRuby bytecode compilers,
  • the JIT compiler being tuned to optimize bytecodes typical of Java programs, and
  • the JVM bytecode architecture being better suited for Java.

I don't know how significant the difference is though.

However, if I write the algorithm in Java and then call it from JRuby, will I still get the performance advantages of java?

Probably yes, but there are some possible reasons why this might not be the case:

  • You might need to convert between equivalent Java and Ruby classes / types at the call boundary, and the cost of the conversions may negate the benefits of recoding in Java.
  • The real performance bottleneck may not be in this algorithm at all.

Before you embark on this exercise of recoding JRuby code in Java, you should do some tests to see if this is a worthwhile exercise at all; e.g. does the application already run fast enough? Then you should profile the application to see if the application is really spending all of its time in the algorithm. Finally, you should see if you can optimize the algorithm in JRuby. (For instance if you can turn an O(N**2) JRuby algorithm with an O(N) JRuby algorithm, then that's better than recoding the original algorithm in Java.)

Stephen C