Performance of the compiled vs. interpreted javascript in java7 / Rhino

前端 未结 3 696
忘了有多久
忘了有多久 2020-12-29 13:45

I have a problem with performance of Rhino javascript engine in Java7, shortly - my script (that parses and compiles texts) runs in Chrome around 50-100 times quicker than t

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 14:00

    The Rhino engine is actually capable of compiling scripts into bytecode 'in-process', so you don't need to run the tool to generate .class files first. You only need to set 'optimisation level' and the engine will automatically pre-compile the script before executing it. One way to override the optimisation level is with the VM argument -Drhino.opt.level. Set this to anything between 0 and 9 and run your original test program and you should see better performance.

    This is the same optimisation setting used by the compiling tool you mentioned, by the way. https://developer.mozilla.org/en-US/docs/Rhino/Optimization

    For total control of optimisation level and javascript version within your program, you can do the following. However you lose some of the trimmings that RhinoScriptEngine class (which is just a environment wrapper and not the javascript engine) provides. One such trimming is the 'print' function which is actually injected by said wrapper. For test purposes you can just replace 'print' with 'java.lang.System.out.print'.

        int optimisationLevel = 3;
        int languageVersion = Context.VERSION_1_7;
    
        try {
            Context cx = Context.enter();
            cx.setOptimizationLevel(optimisationLevel);
            cx.setLanguageVersion(languageVersion);
    
            ImporterTopLevel scope = new ImporterTopLevel(cx);
            cx.evaluateString(scope, TEST_SCRIPT1, "doTest", 1, null);
    
            for (int i = 0; i < 10; i++)
                cx.evaluateString(scope, "doTest();", "", 1, null);
    
        } finally {
            Context.exit();
        }
    

    You mentioned the following:

    Note: some sources mention that Rhino engine runs compiled script roughly 1.6 slower than the "same" code written directly in Java. Not sure if "compilation of script" used in this sample the is same one which is supposed there.

    I'd be interested in the source that reported this, My fibonacci function in java takes about 1/30 the time as the compiled js implementation. But perhaps I'm missing something.

提交回复
热议问题