Calculation of local variable inside a function

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lukas
:warning: 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.

Zylann | 2016-11-05 19:32

:bust_in_silhouette: Reply From: Zylann

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:

{
  "name": "Add two constants"
  "time": 23,
},
{
  "name": "Add 20 constants"
  "time": 267,
}

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.

FYI, the two tests I added:

#-------------------------------------------------------
const CONST01 = 0
const CONST02 = 0

func test_constants_addition():
	start("Add two constants")
	for i in range(0,ITERATIONS):
		var x = CONST01 + CONST02
	
	stop()

#-------------------------------------------------------
const CONST03 = 0
const CONST04 = 0
const CONST05 = 0
const CONST06 = 0
const CONST07 = 0
const CONST08 = 0
const CONST09 = 0
const CONST10 = 0
const CONST11 = 0
const CONST12 = 0
const CONST13 = 0
const CONST14 = 0
const CONST15 = 0
const CONST16 = 0
const CONST17 = 0
const CONST18 = 0
const CONST19 = 0
const CONST20 = 0

func test_constants_addition_extended():
	start("Add 20 constants")
	for i in range(0,ITERATIONS):
		var x = CONST01 + CONST02 + CONST03 + CONST04 + CONST05 + CONST06 + CONST07 + CONST08 + CONST09 + CONST10 + \
		        CONST11 + CONST12 + CONST13 + CONST14 + CONST15 + CONST16 + CONST17 + CONST18 + CONST19 + CONST20
	
	stop()

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.

lukas | 2016-11-05 20:02