I have a singleton script containing global variables. There are separated in two categories: the ones that are set at the start of the game and the ones that may change during runtime (such as sensitivity for example).
Is there a performance difference in always calling Globals.sensitivity in my scripts or doing something like this ? (see below)
In theory direct set the variable is more performant because avoid the call function operation, but in practice if you aren’t doing hundreds of calls per second the difference will be irrelevant
I call it in physics_process so I thought it was worth the optimisation
Anyways I realized I could just benchmark it using the following code and the second solution runs 2x faster than accessing the globals singleton everytime.
const n: int = 10e8
@onready var sens = Globals.sensitivity
func _ready():
var time_start = Time.get_ticks_usec()
test1()
var time1 = Time.get_ticks_usec()
test2()
var time2 = Time.get_ticks_usec()
print("1: ", time1 - time_start)
print("2: ", time2 - time1)
print("1 / 2: ", float(time2 - time1) / float(time1 - time_start))
func test1() -> void:
var t: float = 1.0
for i in n:
t *= Globals.sensitivity
func test2() -> void:
var t: float = 1.0
for i in n:
t *= sens
Output:
1: 91562882
2: 43399067
1 / 2: 0.47398100684511
Thank you for taking the time to read my post even if the question was silly lol