yunabe / tslab

Interactive JavaScript and TypeScript programming with Jupyter
Apache License 2.0
733 stars 45 forks source link

Slow code execution by vm.runInContext #11

Closed yunabe closed 5 years ago

yunabe commented 5 years ago

The execution of code below is slower than Python.

function naiveFib(n: number): number {
    if (n > 1) {
        return naiveFib(n - 1) + naiveFib(n - 2);
    }
    return 1;
}
naiveFib(40);

According to Performance section of this blog:

To avoid this, wrap scripts that you run using runInContext or runInNewContext in a immediately-invoked function expression (IIFE).

we should wrap code with function(){...} for some reason to improve the performance.

Also, the implementation of require in Node.js wraps code with function(){...} and run it with vm.runInThisContext internally (reference). Thus, it seems like we also need to wrap code with function(){...} though I don't understand the exact reason.