I am trying to integrate V8 into my game engine. This is how the engine currently handles the scripts: When the game starts, all the scripts are loaded, compiled and run. After that, the script engine tries to get a pointer to two JS functions called setup
and update
. If the functions exist in the source code, their pointers are placed in two Persistent<Function>
objects. Then the engine calls the setup
function once.
After this, the game loop starts, and my engine tries to call the update
function 60 times per second (timing is handled by VSync, that's why it's 60). This is done with the following code:
void ScriptComponent::Update()
{
if (!script_context->function_update.IsEmpty())
{
v8::Isolate* isolate = script_context->isolate;
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
// script_context->context is a Persistent<Context> and
// script_context->function_update is a Persistent<Function>
v8::Local<v8::Context> context = script_context->context.Get(isolate);
script_context->function_update.Get(isolate)->Call(context, context->Global(), 0, {});
}
}
Everything works fine, but for some reason it brings the CPU usage up to ~20% and the fps down to about 30-45 FPS with occasional lag spikes. But if I comment out this code, I get an average CPU usage of 1% and a solid 60 FPS.
Is there any way I could optimize the code above so it doesn't take that long to execute?
If anyone is having performance issues with V8, make sure you run the program with the Release version and not Debug.