Best practice to clear objects in tables?

Was wondering which way to clear and destroys instances in table is the best for performance and speed wise.

local Objects = {Instances}
for _,v in Objects do
   v:Destroy()
end
table.clear(Objects)
--or
local Objects = {Instances}
for _,v in Objects do
   v:Destroy()
end
Objects = {}
Objects = nil
1 Like

If you plan on using the Objects table again, it might be faster to use the first one, since it does not allocate a new table. However, the speed gain is incredibly minute and probably not worth worrying about. Remember, premature optimization is the root of all evil. The first is probably the most readable one.

2 Likes

How exactly is it faster and what about performance? Do I need to make Objects variable nil after I cleared it with table.clear()? Since the tables I’m using are pretty big and not needed upon a certain condition (e.g Players’ death).

table.clear is more concise, and its pretty explicit what it does: clearing a table. However, again, the more important question is whether this is worth even fussing over. A player’s death is (hopefully) not a frequent occurrence, so it doesn’t matter as much how performant it is.

Just needed to note that, thanks! I’m always afraid of memory leaks, especially on how it’s important to nil a variable after destroying an instance associated with it.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.