Gdscript getter and setter functions performance

Godot Version

4.2.2 stable

Question

im still relatively new to godot and i’ve only used gdscript so far. so far ive been getting and setting properties by just reading from and writing straight to said properties .
ex. print(some_property), property = some_value

im used to doing to this from previous programming experience, and also because most, if not all, godot tutorials ive read so far do things this way as well

but i wanted to try using the special get and set functions that are mentioned in the documentation. for instance, there is:

● Vector2
position [default: Vector2(0, 0)]
set_position(value) setter
get_position() getter

for the first time ive tried to actually use these functions because it would improve readabilty, but it also seems to improve performance!


extends Sprite2D

func _ready() -> void:
	var s := Time.get_ticks_usec()
	for i in 10000:
		set_position(Vector2(100, 150))
	var e := Time.get_ticks_usec()
	print('set_position(): %s' % (e - s))
	
	var s2 := Time.get_ticks_usec()
	for i in 10000:
		position = Vector2(100, 150)
	var e2 := Time.get_ticks_usec()
	print('position property assignment: %s' % (e2 - s2))

	var s3 := Time.get_ticks_usec()
	for i in 10000:
		var x := get_position()
	var e3 := Time.get_ticks_usec()
	print('get_position(): %s' % (e3 - s3))
	
	var s4 := Time.get_ticks_usec()
	for i in 10000:
		var x := position
	var e4 := Time.get_ticks_usec()
	print('position property read: %s' % (e4 - s4))

output:
set_position(): 1835
position property assignment: 2340
get_position(): 846
position property read: 1301

i may have missed this optimisation in this in the docs? now that i think about it, i did read about using built-in functions performing better when using gdscript but i didnt know that extended to these cases as well. this seems fairly useful for use in functions like _process(), _physics_process() and the like. all i know is ive underestimated the importance of using these getter/setter functions for certain

1 Like

That’s interesting. I wonder why the editor completion does not show those set and get functions. I would use those, but without autocomplete it is really more typing.

yes i was always wondering the same thing, autocompletion would really help here, but maybe it would clutter the function list too much? it could be an option to toggle on/off in editor settings.