Bruce Johnson of the GWT team has continued the deep dive into GWT with a posting on a new GWT 1.5 feature: JavaScript overlay types. This feature goes beyond the JNSI technique to “make it easy to integrate entire families of JavaScript objects into your GWT project. There are many benefits of this technique, including the ability to use your Java IDE’s code completion and refactoring capabilities even as you’re working with untyped JavaScript objects.”

// The JSON object gets its Java type implicitly based on the method's return type

privatenative Customer getFirstCustomer(){

// Get a reference to the first customer in the JSON array from earlier

return $wnd.jsonData[0];

}

}

Bruce then shows us some performance wins that you get, as GWT gets to do a lot of inlining:

A quick digression for compiler geeks. Another neat thing about overlay types is that you can augment the Java type without disturbing the underlying JavaScript object. In the example above, notice that we added the getFullName() method. It’s purely Java code — it doesn’t exist on the underlying JavaScript object — and yet the method is written in terms of the underlying JavaScript object. In other words, the Java view of the JavaScript object can be richer in functionality than the JavaScript view of the same object but without having to modify the underlying JS object, neither the instance nor its prototype.

(This is still part of the digression.) This cool wackiness of adding new methods to overlay types is possible because the rules for overlay types by design disallow polymorphic calls; all methods must be final and/or private. Consequently, every method on an overlay type is statically resolvable by the compiler, so there is never a need for dynamic dispatch at runtime. That’s why we don’t have to muck about with an object’s function pointers; the compiler can generate a direct call to the method as if it were a global function, external to the object itself. It’s easy to see that a direct function call is faster than an indirect one. Better still, since calls to methods on overlay types can be statically resolved, they are all candidates for automatic inlining, which is a Very Good Thing when you’re fighting for performance in a scripting language.