Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: V8ScriptEngine.Compile vs. V8ScriptEngine.Script

0
0
I'm trying to wrap my brain around the advantages of compiling a script with V8ScriptEngine.Compile versus dynamically evaluating script code using V8ScriptEngine.Script.

Suppose I have script code like this:
string code = @"
    function computeFoo(foo)
    {
        return (foo.inputA * foo.inputB);
    }
";
In my C# code, I have a class Foo defined as follows:
class Foo
{
    public double inputA { get; set; }
    public double inputB { get; set; }
}
Now, suppose I need to "computeFoo" in a loop over and over again. It seems like I have two choices: dynamic evaluation with the V8ScriptEngine.Script member...
V8ScriptEngine engine = new V8ScriptEngine();
engine.Execute("DynamicJS", false, code);
for (int i = 0; i < 50000; i++)
{
    Foo foo = getFoo(i); // this function returns an instance of Foo
    var result = engine.Script.computeFoo(foo);
    // do something here with result
}
...or I could compile the script code and re-execute the compiled code over and over. But if I do that, it doesn't seem that I can pass any parameters to the "computeFoo" method in my script code. Instead, it seems that I have to do something like this:
string code = @"
    var foo = hostFoo;
    function computeFoo()
    {
        return (foo.inputA * foo.inputB);
    }
    computeFoo();
";
V8ScriptEngine engine = new V8ScriptEngine();
Foo foo = new Foo();
engine.AddHostObject("hostFoo", foo);
V8Script compiledCode = engine.Compile(code);
for (int i = 0; i < 50000; i++)
{
    foo = getFoo(i);
    var result = engine.Evaluate(compiledCode);
    // do something here with result
}
I've done some timing tests, and while the compiled approach is faster, it's not as dramatically faster as I had expected (it's more on the order of 20-30% faster). And if I make the "Foo" class a .NET class such as a Dictionary<>, the speed differential between the compiled and dynamic evaluation approach is narrowed even further.

Considering that parameter passing from C# to the script code is less elegant with the compiled approach vs. using the Script member, I'm almost tempted to ditch compilation. The script code is something that is provided by our customers, and it's much more intuitive to tell them to create a "computeFoo" function that looks something like the first example versus the second one. Or am I missing something fundamental about how to pass parameters to compiled scripts?

Thanks!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images