Exactly how efficient is get_node()?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Rodeo
:warning: Old Version Published before Godot 3 was released.

Is it feasible to use get_node() in the _process() or _fixed_process() callbacks in lots of different scripts? Like if I have 30 scripts which are all calling get_node() in _process(), am I likely to see any performance issues? Should I be storing a reference to the node that I get during the _ready() callback, and using that reference in _process()?

I don’t know, so I can’t answer to your question. But I took the habit to store a reference of nodes I use frequently, typically like:

onready var somenode=get_node("somenode")

Then I only use my reference. So far so good.
And this way, I can change the node name without changing everywhere my code.

Gokudomatic2 | 2016-08-11 20:08

And this way, I can change the node name without changing everywhere my code.

That’s a good enough reason on it’s own to do it. Also, I forgot about the onready keyword.

Rodeo | 2016-08-11 20:52

I usually do it as Gokudomatic2. If you don’t know the performance impact, you can always test it. The 2.1 has a new shiny profiler.

GlaDOSik | 2016-08-11 22:00

That’s true, I could do it in the profiler. TBH I haven’t actually had any problems with performance. I posted the question for posterity as much as anything, so these kinds of best practices are great to put here :wink:

Rodeo | 2016-08-11 22:23

FYI, get_node() looks for all children and tests their name one by one, it doesn’t uses a dictionary or a lookup thing. So the more nodes you have, the slower it will be.
Have a look here: https://github.com/godotengine/godot/blob/master/scene/main/node.cpp#L1589

Zylann | 2016-08-27 00:55

@Gokudomatic2, you should really add this as an answer.

mydoghasworms | 2016-11-03 11:02

I think it is faster by storing the node in a variable. I tested it with two function that simply access to a node and change a parameter (the text in a label node). One function use get_node, the other just used a variable. The average times are:

  • Function with get_node: 0.000044 seconds = 44 microseconds
  • Function without get_node: 0.000005 seconds = 5 microseconds

So by not using get_node we would get 5/44 = 8.8x speedup.

Probably this effect is negligible except in very specific cases, and maybe what @Gokudomatic2 said is more relevant, as other users noted:

And this way, I can change the node name without changing everywhere my code.

garred | 2017-11-10 21:16