Is using Clone().Parent = x a bad practice?

I have a game, which requires lots of objects being cloned in and out of the game. I am very conscious of untracked-memory and optimisation techniques and was curious.

I was looking at this post earlier PSA: Don't use Instance.new() with parent argument and was wondering if this has the same effect? Which would be most efficient and possibly load the fastest?
1.

do
local Obj = replicatedstorage.Obj:Clone()
Obj.Parent = workspace
end

OR 2.

replicatedstorage.Obj:Clone().Parent = workspace

In my older games i used clone().parent = x, alot in fear of creating untracked memory due to assigning the cloned object as a variable.
Thank you!

1 Like

It is the same as Instance.Parent

1 Like

the post said that you should change parent after changing properties.
so unless you are changing the properties, creating a clone and setting the parent in the same line is efficient.

1 Like

If you don’t do anything special with the cloned object like using .touched events or storing them in a table, the variables will for sure get GC’d and you’ll be fine. If you do things like connect events, the variables will also be freed from memory if you call :destroy() on the cloned objects as it disconnects such events. In other words, unless if you’re doing something pretty technical with the objects you’re cloning, they are pretty safe to use.

If you’re worried about optimization in general, maybe try caching objects using a module like partcache? I think repositioning parts via cframe is a lot faster than cloning/parenting/positioning for every object you need, but this should only matter if you’re cloning many objects very quickly.

4 Likes

Thank you. I understand now. Though the majority of objects that I clone are just for visual needs and not connections, so is there a preferred way to clone objects for this reason? *out of the two options I mentioned above?

I suppose on the most micro-level possible that option 2 (clone().parent) is technically easier on memory, but it’s really not going to make much of a difference, either are fine.

2 Likes