I wish to develop a JavaScript game engine that uses C++ as a back-end for rendering/updates/collision etc. Pretty much all the heavy lifting stuff.
There would then be C++ classes/functions that are exposed through modifying the isolate
variable (or maybe just a native nodejs module). Some of these classes, like the Sprite
class, could have its update
function overridden by a JS subclass in order to allow users to customize the behavior.
Finally, the game engine would run in a loop within the JavaScript, but every frame would make a call to the C++ context to update/render and all the stuff PLUS there would be tons of calls to check input, collision, etc. Not to mention all the callbacks each subclass would make to the parent classes written in C++.
My concern is that I have read there is significant overhead (more than normal) when calling C++ from the JS context (be it ffi or native modules). Usually it's worth it for the performance, but considering how many calls would be made back and forth between the two languages each frame, perhaps this wouldn't be the best idea? Instead, maybe something like Python would be more appropriate due to its zero overhead (though Python in general is much slower), or a different JS interpreter all together?
This answer is going to be very subjective, it's from observations from my experience that I wouldn't say are very rigorous, I'm working through this issue now myself, and i have not verified my claims with benchmarks. That said...
Yes, calling from JS to C++ is relatively expensive. Certainly more so than calls within pure JS. Substantially more so, in fact, than calls in the other direction, from C++ to JS. I assume that a major cause of the inefficiency is that the javascript engine loses some optimization opportunities.
However, assuming you stick with the V8 engine, calls from JS to C++ will be much faster than calling out into any other language.