Closed XmiliaH closed 1 year ago
Thank you for putting this together, I was able to try it out for our use case and compare it to the optmizaiotn you suggested in https://github.com/patriksimek/vm2/issues/514#issuecomment-1496607700.
I used hey to test our service with the various implementations.
The actual code we have is a bit more involved, but roughly this is the current implementation we have with your optimization from #514
let _resolver: Resolver
const script = new VMScript(`module.exports = require('./bundle.js');`);
function render(args) {
const vm = createVM();
const handler = vm.run(script);
return handler(args);
}
function createVM() {
const vm = new NodeVM({ require: { external: true, root: './'} })
cacheResolver(vm)
return vm
}
function cacheResolver(vm: NodeVM) {
if (!_resolver) {
_resolver = vm._resolver
} else if (vm._resolver) {
try {
Object.assign(vm._resolver, {
packageCache: _resolver.packageCache,
scriptCache: _resolver.scriptCache,
})
} catch (error) {
report(error)
throw error
}
}
}
Again, this cuts out some details, but this is roughly what my implementation of this makeResolverFromLegacyOptions
API looks like
let _resolver: Resolver
const script = new VMScript(`module.exports = require('./bundle.js');`);
function render(args) {
const vm = createVM();
const handler = vm.run(script);
return handler(args);
}
function createVM() {
const resolver = getResolver()
const vm = new NodeVM({ require: resolver })
return vm
}
function getResolver() {
if(_resolver) return _resolver
_resolver = makeResolverFromLegacyOptions({ external: true, root: './'})
return _resolver
}
The API you propose here gives me the same run-time characteristics, and a nicer API 👍
I'd say it's a winner 🏆
Thanks for the feedback
Oh and for comparison, if I don't cache the resolver at all, I eventually start to error if I try to make 100 consecutive requests, but at 19 requests I see the following
So you can see that caching the resolver is a huge improvement for us!
Add resolver API allowing to share resolvers for multiple
NodeVM
instances.A new resolver can be created with
makeResolverFromLegacyOptions
.