CollectionService VS for loop

So if you know CollectionService, you will know that it’s a great way to organize codes. For example, making a script that gives the ability of tagged parts to kill whoever is touching it:

local CS = game:GetService(“CollectionService”)
local tagged = CS:GetTagged(“Kill”)

for i,v in pairs(tagged) do
    v.Touched:Connect(function(hit)
        if game.Players:GetPlayerFromCharacter(hit.Parent) then
            hit.Parent.Humanoid:TakeDamage(100)
        end
    end)
end

But however, while I was learning it. I was thinking, why couldn’t you just use a for loop without the service? For example:

for i,v in pairs(game.Workspace:GetChildren) do
    if v:IsA(“Part”) and v.Name == “KillBrick” do
        v.Touched:Connect(function(hit
            if game.Players:GetPlayerFromCharacter(hit.Parent) then
                hit.Parent.Humanoid:TakeDamage(100)
            end
        end)
    end
end

If possible, what’s the use of CollectionService if for loops could do the job?

Which one should I use for my game?

What’s the difference between both of this?

If you can answer all the questions, thank you for enlightening me!

1 Like

While the speed difference may or may not be negligible, by using tags you only set specific instances that will have the tag, and obviously the entire workspace wouldn’t have this tag. So less instances to iterate through

So it would be a bit faster to use tags, more organized so if for whatever reason you can’t have all the kill bricks in 1 place, you can just tag each brick and it won’t matter where it is.

Also notice how in a good way the CollectionService code sample was shorter since you didn’t need to check if it was a part and that it was named KillBrick.

5 Likes