ChaiScript
ChaiScript copied to clipboard
Slow implicit type conversion
- Compiler Used: MSVC 2015
- Operating System: Windows 10
- Architecture (ARM/x86/32bit/64bit/etc): x64
I am creating a function in script that pushes back a std::vector<double>. In some cases I handle State classes that can be implicitly cast to double, so I've registered this type conversion with ChaiScript:
add(chaiscript::type_conversion<State&, double&>());
My issue is that ChaiScript's handling of this implicit cast is very slow compared to explicitly casting to double. It typically wouldn't be an issue, but this cast is occurring every time step, and therefore hundreds or thousands of times a second.
Here is the script function for creating and saving the std::vector<double>:
rec.record = fun[rec, sim, lorenz]() { rec.push_back([sim.t, lorenz.x0, lorenz.x1, lorenz.x2]) }
In this case x0, x1, and x2 are States that are implicitly cast to double.
To compare, I created an explicit cast to double with a value() method:
add(chaiscript::fun([](State& state) { return static_cast<double>(state); }), "value");
The same function in script with explicit casting:
rec.record = fun[rec, sim, lorenz]() { rec.push_back([sim.t, lorenz.x0.value(), lorenz.x1.value(), lorenz.x2.value()]) }
The time difference in Release between the two methods is: Implicit casting: 26.74 s Explicit casting: 2.62 s
So, explicit casting is about ten times faster in my test case.
My question is whether it is possible to improve the performance of implicit casting, or will explicit casting always be faster? I'm dealing with performance sensitive code, and although I like the reduced syntax of implicit casting, speed is of primary concern.
Explicit will always be faster. At runtime ChaiScript essentially has to try everything else first then it tries possibilities that include conversions. After determining which conversion to use, it must save a pointer to the object that was used in the conversion, to make sure the original object's lifetime is extended. Then after the function call it must deal with decrementing the pointers and popping the saves from the stack.
I have done a few passes over the implicit conversion code to make it faster in the past, but haven't looked at it recently. If you can post a self contained example that exercises the slowdown you are concerned about, I can take another pass over it and see what I can find.
Thanks for describing the implicit conversion process. Since explicit conversion will always be faster, then I'll just enforce explicit casting in this case.
You can close this issue, as I'll just use explicit casting in critical sections of script.
I'll probably leave it open just to revisit it and double check I'm not doing something dumb.