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.