Is there any performance issue when using $ and % directly? Here’s the example:
func _process(delta: float) -> void:
for ch in %SomeNode.get_children():
ch.position = %Coordinates.position
Does the following script have better performance (like hundreds of loop) or just same?
@onready var _some_node:= %SomeNode
@onready var _coordinates:= %Coordinates
func _process(delta: float) -> void:
for ch in _some_node.get_children():
ch.position = _coordinates.position
Those are shorthands for a get_node() call. So you could save some performance by not doing it in a loop, although the engine might still optimize it under the hood. It’s easy enough to benchmark this on your own.
(Google translator)
I assume that you could look at the Godot source code to see the implementation of each case.
I suppose that “$” will be more expensive because you can put a path, which must be processed, until the desired node is obtained and that will involve traversing the nodes of the tree and that “%” will be an access to the node through some type of hash table.
You can always run it many times and set times to see if any improvement is seen.
I, personally, always prefer to create my own references to the nodes and create them in the _ready (or onready) using “%” (your second option). This way I can relocate the nodes without problems, forgetting about their paths and I am not asking the engine to continually search for them.
I had expected there were some quick answers but looks everyone suggest me doing the experiment, here it is!
for i in 100000:
$path...
Took 33ms.
var n = $path
for i in 100000:
n...
Took 19ms.
for i in 100000:
%name...
Took 28ms.
var n = %name
for i in 100000:
n...
Took 19ms.
So my conclusion is, using $ and % in script directly does have cost but it is very tiny. As long as you don’t have it in the loop repeating thousands of times, you should be fine with it.
A little surprise that % doesn’t have much performance gain in comparison to $. I had thought % may utilize some cache but…anyway.
You could also run versions with get_node() to check if its indeed the same thing. Also a difference between $ and % for paths of various depths would be nice to see.
Yeah, some friends also mentioned this to me. In my test, $path is just a 3-level-depth thing and the whole scene is not complicate with hundreds of nodes.