Topic was automatically imported from the old Question2Answer platform.
Asked By
lukas
Old Version
Published before Godot 3 was released.
Consider a scenario that a following function fn() is called multiple times.
func fn():
var x = CONST1 + CONST2
where CONST1, CONST2 are globally defined constants. Is value of x calculated every time the function is called or just once during a scene initialisation?
I think CONST1 + CONST2 will be expanded to an addition of two numbers, which will be resolved at compilation time. But I have no sources to prove it.
A good way to test this would be to find if CONST1 + CONST2 takes the same time as CONST1 + CONST2 + CONST3 + CONST4 + CONST5 + CONST6 + CONST7 + CONST8 + CONST9 + CONST10 + CONST11 + CONST12 + CONST13 + CONST14 + CONST15 + CONST16 + CONST17 + CONST18 + CONST19 + CONST20.
Verified answer: value is calculated every time D:
I used the test shown in my comment above and this is the results from my performance project, in built release:
As you can see, adding 20 constants is much slower than adding 2. But in reality this should not be different since it’s just constants added together.
I think the reason why it’s not precalculated is that the result is stored in a var, and the optimizer is not clever enough to merge the additions into a simple assignment.
Thanks! So there is a room for optimisation of GDScript :). So it seems to me that everything that can be precalculated and is not planned to change during a game is better to put to global scope of the scene. But it can make code quite opaque to have global variables that are only used inside a function.