Alternative to 'FindFirstChild'

So, I’ve been told by a few experienced scripters that using Find First Child a lot is bad and I’ve recently seen evidence of that in this post:

image

I’m trying to make a combat system that I’m working on as performant as possible to deal with lots of players. It currently takes 0.5 MS to perform actions but I want to get it lower. I assume my use of FindFirstChild is the issue.

What do I use as an alternative?

As the script says, if it isn’t necessary to be faster, keep it in. If your code is dependant on findfirstchild, keep it in.

Else, as the post says, store the variable or find it by using the ChildAdded or WaitForChild.
(From post you referenced)

That says it all.

Well, I recommend to put your code in a ‘Code Review’ topic if you want to optimize it. I highly doubt that FindFirstChild is a problem at all. If you truly wish to optimize your code then try to see if you can improve the time complexity of it. Usually, slow code is mainly caused by operations in nested loops.

:WaitForChild() is a good alternative which achieves a similar task/goal.

I think you’re missing the key context here. It’s not that the function is bad, should be avoided or that there’s some secret alternative that nobody is telling you about…


Using FindFirstChild or WaitForChild to get your first reference to something is fine, but if you’re going to reference that instance again and again then store a reference to it in a variable.

Example of unnecessary FindFirstChild usage (9 calls):

if workspace:FindFirstChild( 'BanTech' ) then
    if workspace:FindFirstChild( 'BanTech' ):FindFirstChild( 'Humanoid' ) then
        workspace:FindFirstChild( 'BanTech' ):FindFirstChild( 'Humanoid' ).WalkSpeed = 30
        workspace:FindFirstChild( 'BanTech' ):FindFirstChild( 'Humanoid' ).HipHeight = 3
        workspace:FindFirstChild( 'BanTech' ):FindFirstChild( 'Humanoid' ).Sit = true
    end
end

Faster way to achieve the same thing (2 calls):

local bantech = workspace:FindFirstChild( 'BanTech' )
if bantech then
    local humanoid = bantech:FindFirstChild( 'Humanoid' )
    if humanoid then
        humanoid.WalkSpeed = 30
        humanoid.HipHeight = 3
        humanoid.Sit = true
    end
end

It’s plain to see with an example exaggerated like this - when code is a bit more complex and spread out it may be harder to realise, but the essential tip is:

Don’t throw away results to expensive calls - always store them if you need to keep using them.

If you know the instance exists with 100% certainty, use the dot operator instead, but if you’re unsure, do ONE call to FindFirstChild (or similar) and store the result!


That’s it. There’s no secret trick or magic sauce, just think about it logically knowing that the calls are expensive and should be used only when necessary and not excessively.

2 Likes