Using ClearScript, what is the absolute FASTEST way to call a C# method in JavaScript (and vice versa)? #670
Replies: 1 comment
-
How you expose a host object to the script engine – be it via In your examples above, you're exposing delegates, which is a good idea if performance is a concern, as script code can invoke a delegate in just one hop across the boundary and without triggering the costly method binding algorithm. ClearScript's caching can reduce the average overhead of normal method invocation for a given object, but like all caching schemes, it has limitations. So, when it comes to invoking managed code from script code, you're in good shape. The only potential improvement is to use the new FastProxy API in ClearScript 7.5, especially if the managed code you're exposing takes arguments and/or returns data to the caller. Here's a sample that demonstrates the FastProxy improvement: Func<int, double, double> myMethod = static (a, b) => {
return a * b;
};
V8FastHostFunctionInvoker myFastMethod = static (bool _, in V8FastArgs args, in V8FastResult result) => {
var a = args.GetInt32(0);
var b = args.GetDouble(1);
result.Set(a * b);
};
engine.AddHostObject("myMethod", myMethod);
engine.AddHostObject("myFastMethod", new V8FastHostFunction(myFastMethod));
engine.AddHostObject("sw", new Stopwatch());
engine.AddHostType(typeof(Console));
engine.Execute("""
const iterations = 1000000;
sw.Start();
for (let i = 0; i < iterations; i++) {
myMethod(i, i * 0.5);
}
sw.Stop();
Console.WriteLine(`myMethod: ${sw.ElapsedMilliseconds} ms for ${iterations} iterations`);
sw.Restart();
for (let i = 0; i < iterations; i++) {
myFastMethod(i, i * 0.5);
}
sw.Stop();
Console.WriteLine(`myFastMethod: ${sw.ElapsedMilliseconds} ms for ${iterations} iterations`);
"""); On our test machine, it produces the following output:
As you can see, it's a significant improvement for the delegate vs. fast host function case.
That's currently the best you can do. The most important thing is to avoid script parsing and/or compilation, and you're doing just that by invoking an existing script function. Unfortunately, ClearScript currently doesn't have a FastProxy-like way to accelerate argument passing in this direction, but we're hoping to add that in a future release. Good luck! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm currently calling C# methods in JavaScript like this:
And vice versa I'm calling JavaScript methods in C# like this:
My question is, is there a FASTER or more optimized way to call methods across the runtime boundaries?
I.e., is there a better alternative than using
engine.AddHostObject()
for calling C# in JS, and usingScriptObject.InvokeAsFunction()
for calling JS in C#?Beta Was this translation helpful? Give feedback.
All reactions