Hi, I have done some performance testing for my game.

I have a scene consisting of a static body, sprite and collision shape. The sprite texture is set at runtime because the levels are generated procedurally. I would like to know why Code A is up to 10 times faster than Code B.

~~A:

// scene
PackedScene scene = (PackedScene) GD.Load("res://Scene1.tscn")

//later in the code i'm calling this in a loop quite often
s = scene.Instance()
Sprite sprite = s.GetNode<Sprite>("Sprite")
s.texture = (Texture) GD.Load("res://Scene1.png")
AddChild(s)~~

B: Here an array/Dictionary of scenes is used where each scene has the correct texture loaded.

PackedScene[] scenes = new PackedScene[10]
//... init scenes e.g. scenes[2] = (PackedScene) GD.Load("res://Scene2.tscn")

// now in the code called in a loop very often:
s = scenes[i].Instance()
AddChild(s)

I'm really surprised that A is so much faster than B. Is it because of the garbage collection etc and GD.Load being well optimized? I have done a bit more testing and now found out that B is faster than A or it's dependent on the situation.

Also I would like to know if there is even a better method if I need to load a great amount of scenes at runtime as this is quite slow. It takes about 0.1 second to load 100 scenes. Maybe a packed scene is the wrong approach to do this? A tilemap is not an option because I have destructible environment and replacing / removing a tile costs more time than this solution. I also know that I should put this inside a separate thread so it can be loaded in the background but still I would like to have this code optimized for best performance.

12 days later

I would hazard to guess preload instead of load to suck all the scenes into the game at launch.

You can also handle 'background' loading by using a Timer node to load one or more scenes in batches. If scenes are needed circumstantially you can classify them and load only the bunch you need right away.

You might also try 'pre load batching' where you have packed scenes that exist only to preload sets of other scenes when the 'batching' scene is itself loaded into the game. This may give you memory/speed trade offs you want. (Note however, this is an untested idea on my part, but if a scene itself preloads scenes, then that preload only occurs when the packed scene is itself loaded)

2 years later