Subj : Re: Performance: How does accessing a method in a Java class work? To : Neil Kolban From : Igor Bukanov Date : Tue Oct 14 2003 07:49 pm Neil Kolban wrote: > Folks, > I am looking into embedding Rhino ... > > I want to be able to script access to Java objects. > > As a test, in my JavaScript, I create a class, and call a member in the > class 20,000 times: > > var myObj = new MyClass(); > var i = 1; > while (i<20000) > { > myObj.myMethod("ABC"); > i = i + 1; > } If you will put your code in a function like function test() { var myObj = new MyClass(); var i = 1; while (i<20000) { myObj.myMethod("ABC"); i = i + 1; } } test(); then Rhino will get a chance to optimize i = i + 1 from something like: Object tmp = lookupProperty("i") Object tmp2 = new Double(((Integer)i).intValue()); setProperty("i", tmp2) to something that is not significantly slower then i = i + 1 in Java. Then you will get more fair comparison with Java method. > > In Java, I perform the same task: > > MyClass myObj = new MyClass(); > int i = 1; > while (i<20000) > { > myObj.myMethod("ABC"); > i = i + 1; > } > > In Java, the loop takes 60 msecs. In JavaScript, the loop takes 500 msecs. > > So .. my question is, what does JavaScript "do" when it wants to call a > method? Does it go through an introspection / reflection each time? It will go via reflection each time. > Is > there some technique I can use to improve the underlying performance? If you define a host object explicitly as described in http://www.mozilla.org/rhino/tutorial.html#DefiningHostObjects and not rely on direct Java scripting, then Rhino will generate a special classes at runtime to invoke host objects functions by at least 2 times faster compared with JDK 1.4.2. To get even better performance you can do explicit switch over strings as Rhino does for most of its internal classes. Rhino CVS tip also contains few optimizations that may help in your case. Regards, Igor .