On Tue, May 17, 2011 at 10:02 AM, John Cowan <[email protected]> wrote: > FWIU, the optimal approach if you are batch-compiling is to stuff N > functions into a single class as static methods using this sort of > framework: > > public class FooBarBaz { > private int _function; > private FooBarBaz(function) { _function = function; } > public static final fooFunction = new FooBarBaz(0); > public static final barFunction = new FooBarBaz(1); > public static final bazFunction = new FooBarBaz(2); > private static Object foo(Object arg) { ... } > private static Object bar(Object arg) { ... } > private static Object baz(Object arg) { ... } > public Object apply(Object arg) { > switch (_function) { > case 0: return fooFunction(arg); > case 1: return barFunction(arg); > case 2: return bazFunction(arg); > } > }
I don't know if I'd say optimal. Different JVMs optimize switch/case very differently, and in JRuby we have in some places avoided switches because after a certain size Hotspot seems to optimize them very poorly. This form is optimal for code size and number of classes (and is similar to JRuby's mechanism in that all bodies are simply static methods in a "bag of methods" class), but the switched dispatch is often suboptimal. You also need to consider that JVMs have thresholds for the size of method they're willing to inline. A very large switch may never inline, where small stub classes usually will. Optimal for both size and performance is to generate the bodies into static methods as above, but use either unique stub classes as the function objects or use JSR292 method handles to bind them. > Note that all functions in a given class need to have the same > Java-level type signature. You can avoid this by using Object[]s, but > that's additional overhead. For different arities of calls, you can generate different switches. I have intended to do this in JRuby for small-footprint devices (where a class-per-function is too much), and would split arities 0, 1, 2, 3, N and a few other characteristics (pre/post logic like framing, associated Ruby version, etc) into several switches. - Charlie -- You received this message because you are subscribed to the Google Groups "JVM Languages" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/jvm-languages?hl=en.
