If you haven’t read the PSA about Instance.new, read that first, as this post will be discussing that.
Now, this doesn’t just mean “don’t use the parent argument for Instance.new”. I’ve seen quite a lot of people coding like this:
local part = Instance.new("Part") part.Parent = workspace part.Size = Vector3.new(10, 10, 1) -- more properties being set...
This is still a performance waste and you haven’t improved anything.
The whole point of not using the parent argument for Instance.new is to set the properties of the instance before parenting it. As you can see in the code above, that’s not what it was doing.
In the PSA post referred to above, the author explained the steps that went through when using the parent argument:
- You create a Part with the CFrame of 0,0,0 and a default Size, and parent it to workspace.
- ROBLOX sets up property change listeners for replication, rendering, etc.
- ROBLOX queues a replication of a new instance with default values for the Size/CFrame
- ROBLOX updates physics contacts between this part and whatever is at the origin
- You set the part Size to 10,10,1
- ROBLOX queues a replication change for the Size
- ROBLOX updates physics contacts between this part and whatever is at the origin and overlaps with the part given the new dimensions
You’re going through the exact same steps even without using the parent argument because you’re still parenting the instance before setting all the properties.
The more efficient way to do this (which is also the point of the post) is to parent the instance after setting the other properties, as similarly shown in the referred post:
local part = Instance.new("Part") part.Size = Vector3.new(10, 10, 1) -- more properties being set... part.Parent = workspace
If you’re just going to set the Parent property directly after creating the instance, it would basically be the same thing as using the parent argument, performance wise.
Some people might think that this post is unnecessary as the referred post already explains this and that’s what I thought at first too, but I kept seeing more and more people misunderstanding it and I had to make a topic about it.
TL;DR: The parent of new instances should be the last property to be set, not first.
By the way, this is my first DevForum post, and I’ve been looking forward to it.