Skip to content

Creation of many temporary arrays when calling Java methods in a compiled Javascript #507

@A-Herzog

Description

@A-Herzog

When executing a compiled Javascript and calling a Java method with one parameter, an Object[1] array is created each time. The idea of using compiled methods is to be able to execute the same Javascript code many times fast. Having the garbage collector to remove these many Object[1] arrays slows down the process.

Here are two methods which could be optimized to make Rhino faster (by using significant less memory):

org.mozilla.javascript.optimizer.OptRuntime:
changing

public static Object call1(Callable fun, Scriptable thisObj, Object arg0, Context cx, Scriptable scope) {
    return fun.call(cx, scope, thisObj, new Object[]{arg0});
}

to

private static ThreadLocal<Object[]> paramCall1Cache=new ThreadLocal<Object[]>(); 
public static Object call1(Callable fun, Scriptable thisObj, Object arg0, Context cx, Scriptable scope) {
    Object[] obj=paramCall1Cache.get();
    if (obj==null) {obj=new Object[1]; paramCall1Cache.set(obj);}
    obj[0]=arg0;
    return fun.call(cx, scope, thisObj, obj);
}

and

org.mozilla.javascript.ScriptRuntime:
changing

public static Number wrapNumber(double x) {
    if (x != x) return ScriptRuntime.NaNobj;
    return new Double(x);
}

to

private final static Double[] fastBoxing=new Double[100];
static {for (int i=0;i<fastBoxing.length;i++) fastBoxing[i]=Double.valueOf(i);}
    
public static Number wrapNumber(double x) {
    if (x != x) return ScriptRuntime.NaNobj;
    final long xInt=(long)Math.floor(x);
    if (xInt-x==0 && xInt>=0 && xInt<fastBoxing.length) return fastBoxing[(int)xInt];
    return Double.valueOf(x);
}

decreases memory consumption in a test scenario in Flight Recorder by nearly 75% (5 GB down to 1.31 GB). Also org.mozilla.javascript.optimizer.OptRuntime.call2 could be changed in the same way as call1.

Metadata

Metadata

Assignees

No one assigned

    Labels

    PerformanceIssues related to the performance of the Rhino engine

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions