-
Notifications
You must be signed in to change notification settings - Fork 314
Description
Hello,
I'm hoping you can help me with this question. I'm trying to optimize the performance of calling vm.run().
I have an SSR server where I want to create a new context for every render. I am using VM2 to create a sandbox for my render. However I am noticing that state is leaking (eg variables declared in module-level scope) between renders. I need render requests isolation, and have been looking at creating a new vm context in which to run the script for every render request.
This looks something like:
let script;
function render(args) {
script ??= new VMScript(`module.exports = require('${handlerPath}')`) // this takes a couple ms and can be cached between renders
const vm = new NodeVM(options) // this takes a couple ms. I recreate this on every render to not leak state between renders
const handler = vm.run(script) // this takes > 1s!!! And needs to be done on every render
return handler(args)
}I think the obvious place I'm looking to optimize is in vm.run. So I am looking for any advice about how to optimize this. Alternatively I would be open to any other patterns that would ensure that state (globals, module scope vars etc) don't get shared between renders in a more performant way.
Thank you in advance for any help you can provide!