Na Na -
[Forward Reference Note: JRuby/Java Bridge Benchmark code and results at
I should have mentioned, there may be ways you can code your JRuby to be
faster too, so you can minimize the need to use Java. Having more JRuby
and less Java would, in my opinion, be a good thing, for all the reasons
that we choose to code in JRuby.
As one example, when JRuby calls a Java function and passes Ruby objects
to it, JRuby may need to create Java objects for those parameters (e.g.
strings and numbers). If the return value is a Java object, JRuby may
need to create a Ruby object with its value.
Consider this JRuby irb session:
jruby-1.7.2 :011 > 2.class
jruby-1.7.2 :001 > java.lang.Math.max(2, 3)
(irb):2 warning: ambiguous Java methods found, using max(long,long)
jruby-1.7.2 :002 > x = java.lang.Math.max(2, 3)
jruby-1.7.2 :003 > x.class
=> Fixnum # a Ruby object, not the Java object actually returned by
A lot is happening here to bridge JRuby with Java:
In Ruby, the numeric value 2 would be represented as an instance of
the Fixnum class. When we pass it to a Java function, JRuby needs to
create a Java object or primitive whose value is 2.
When JRuby receives the return value from the called function, it
will create a Ruby Fixnum that corresponds to it, and substitute that.
This can be avoided by avoiding crossing the Ruby/Java bridge, by doing
it all in either one language or the other. Ruby has min max built into
the Enumerable module, so you could do this:
jruby-1.7.2 :014 > [3,4].max
but that requires instantiating an array and initializing it with the
values, which consumes memory and CPU. Better, I think, to just define
a function and call it, so that Java isn’t needed at all:
jruby-1.7.2 :015 > def max(a,b)
jruby-1.7.2 :016?> a >= b ? a : b
jruby-1.7.2 :017?> end
jruby-1.7.2 :018 > max(7,8)
Of course, this is a contrived example, since one wouldn’t normally
consider it necessary to use Java to get a maximum, but it does
illustrate the bridge overhead, and also the fact that using Java can be
slower sometimes because of it.
I just spent some time playing with benchmarking various approaches. If
you’re interested, check out https://gist.github.com/4580344. Among
other things, it shows that even crossing the JRuby/Java bridge, you can
improve performance ten times by using JRuby’s java_method to specify
which overload to use.
In any case, if you have any cases that can be distilled down to a few
lines of code, you could ask here.
Keith R. Bennett
Work Status: Available