Why is there a lag when creating a template instance for the first time?

This came through a private message and thought it be good to have it answered publicly.

In this project: https://playcanvas.com/project/1003111/overview/f-instantiateclonedebug

Pressing space creates a new instance of the template and adds it to the screen.

There is a ‘lag’ on some devices when the very first instance is created.

To see what is going on, we use the Performance profiler to measure what is being called and why it’s taking so long: Analyze runtime performance - Chrome Developers

There are 3 main costs on the first time load:

  1. _parseTemplate with is called only on the first time instantiate is called and then the data is cached in the engine (see engine/template.js at main · playcanvas/engine · GitHub)

  2. Compiling the shader for the material(s) being used in the template

  3. Initialising the components in the Entity such as adding rigidbodies to the scene

We can get around these in several ways depending on your preference:

Having the object already enabled in the scene at start and then cloning the entity when needed will prevent 1 and 2 happening. (The object can be disabled after the first render frame).

It no longer parses the template as it’s not used in code and the cost of the material shaders is moved to be at start of the application/scene load.

You could also use object pooling and have a fixed number of objects already in the scene that are reused. This moves the cost of 3 to be at start of the application/scene load. This prevents issues 1 and 2 for the reasons mentioned above.

If you still want to use templates, you could instantiate a template at the start of the application and disable/destroy after the first render frame. This prevents 1 on any future calls and also means that the materials in 2 are already compiled too.