dop251 / goja

ECMAScript/JavaScript engine in pure Go
MIT License
5.57k stars 376 forks source link

Is it normal for this JavaScript code to run slowly? #604

Closed jwwsjlm closed 2 months ago

jwwsjlm commented 2 months ago
function f980101(w980, w981, w983) {
    var sum = w983;
    var j = 0;
    var mm = 0;
    for (var i = w980; i <= w981; i++) {
        j++;
        mm = j * j;
        sum += i * 42;
    }
    return sum;
};

function caleResult() {
    return f980101(0, 580176, 980)
}

Goja Implementation

func JsRun() (string, error) {
    jsstr := `function f980101(w980,w981,w983){var sum=w983; var j=0; var mm = 0;for(var i=w980; i<=w981;i++){j++; mm = j*j;sum += i*42;} return sum;};function caleResult(){return f980101(0,580176,980)}`
    Vm := goja.New()
    if _, err := Vm.RunString(jsstr); err != nil {
        return "", err
    }
    cale, ok := goja.AssertFunction(Vm.Get("caleResult"))
    if !ok {
        return "", errors.New("json,error")
    }
    res, err := cale(goja.Undefined())
    if err != nil {
        return "", errors.New("jsvm,error")
    }

    return res.String(), nil
}

Run on my computer. Single time is about 200 milliseconds? Is it too slow?Or is there something wrong with my wording? I7 8700K

dop251 commented 2 months ago

In short, yes. The compiler does very few optimisations (for example, it cannot work out that you don't need j or mm) and the virtual machine does not compile anything to native code, so it mostly runs at interpreter speeds. Even if you leave the loop body empty it will probably still take around 100 ms.

Also, see https://github.com/dop251/goja?tab=readme-ov-file#why-would-i-want-to-use-it-over-a-v8-wrapper