paulbartrum / jurassic

A .NET library to parse and execute JavaScript code.
MIT License
868 stars 121 forks source link

Possibility to create 'sessions' #221

Closed OliwerXi closed 1 year ago

OliwerXi commented 1 year ago

In the latest version, is it a possibility to create sessions to re-use a single ScriptEngine instance and avoid having to set global functions and calling them accordingly? Basically per-session function definitions. I have been reviewing the opened and closed issues regarding this, alongside the Wiki. Any assistance is greatly appreciated.

paulbartrum commented 1 year ago

I may be misinterpreting what you mean by a "session"; this is not a JavaScript concept as far as I know. Are you referring to the global state? In that case a ScriptEngine is a session, as essentially the whole purpose of the ScriptEngine class is to keep track of the JS global state. What it doesn't do is track what has changed in the global state, so the only way to reset it to a known state is to create a new ScriptEngine instance and then initialize it. (If you are doing this a lot then you may be able to speed it up a bit by using compiled scripts.)

OliwerXi commented 1 year ago

Yeah so basically what I was referring to is more or less standalone 'scope definitions' to avoid re-initializing the ScriptEngine. I may be overthinking this, but would it not be a fair bit more expensive to re-instantiate & initialize the instance rather frequently? In my case I process requirements for a command system using the engine, which means that this operation could be called upon more or less anytime, however many times, depending on the user(s) executing commands.

paulbartrum commented 1 year ago

but would it not be a fair bit more expensive to re-instantiate & initialize the instance rather frequently?

It is expensive, yeah, on my computer it takes about 60ms just to initialize the a new ScriptEngine instance, and that's not including any extra initialization you might need to do. Unfortunately if you require a freshly initialized ScriptEngine there's no mechanism in Jurassic that'll speed this up. That doesn't mean there aren't things you can do, however:

OliwerXi commented 1 year ago

Okay, that's given me some insight on how to go about this the best way possible. I appreciate the assistance, Paul!