I have big JavaScript-library that I want to use within my C#-project and it works like a charm using the Microsoft.ClearScript.V8
-nuget and the following code:
public int InvokeJavascript(int parameter)
{
string libraryCode = System.IO.File.ReadAllText("library.js");
string libraryInvokeCode = $"inoke({parameter})";
string javascriptCode = $"{libraryCode};{libraryInvokeCode}";
using (var engine = new V8ScriptEngine())
{
var result = engine.Evaluate(javascriptCode);
return int.Parse(result.ToString());
}
}
The problem is, that the performance is really poor. I would love to compile the code for the JavaScript Library only once and the invoke on the compiled script to avoid compiling it with every invoke.
Do you have any idea how I can do that?
2
Answers
You may utilize
V8ScriptEngine.Compile
method and host parameter like thisremeber to keep
script
andengine
not disposed, for example you can nicely wrap it around some class like this:and use it like this:
You’re re-reading the library file, re-instantiating the script engine, and re-executing the library code for each call. Caching the engine lets you make multiple calls without all that overhead:
Usage example: