Is it more convenient to pass an object instance or its instance id?

Godot Version

4.4

Question

I’ve got a doubt about parameters and how to pass them.
My purpose is of course memory and performance optimization.
Let’s say that I have instantiated some objects consisting of a Node3D containing a StaticBody3D, a CollisionShape3D, a MeshInstance and other nodes. I need to pass to a function those of these objects which and when satisfy a condition to store them inside an array, later I will need to pick objects from this array.
Which of these solution would be better?

  • Call a function add_object(my_object) where my_object is the object’s instance
  • Add the object to the array objects.append(my_object)
  • When I need the object I just pick it from the array

or

  • Call a function add_object(my_obj_id: int)
  • Add the object’s instance id to the array
  • When I need the object call instance_from_id(my_obj_id)

You could benchmark to see, but I suspect the answer is a wash; I’m assuming you’re using GDScript here. I think you’ll probably find that the difference between the two is largely lost in the interpreter overhead.

That said, I’d suggest testing it and seeing if you can see a difference; there may well be one.

1 Like

In your first example, you’re not passing an entire object into your function and array, but just a reference (memory address) to that object. This basically shouldn’t make any dent on the memory and should be almost identical to the second example, while arguably more elegant and easier to use.

If you’re truly worried about memory, then as @hexgrid suggested, only testing will make it clear.

Thank you, this helps to understand what happens and tells me to use the first solution.
I am not that concerned, at least at the moment, about memory and performances, but being a beginner and knowing that optimization for games is something to be worried about I had this doubt.

1 Like