Referencing and :WaitForChild()

Is not calling :WaitForChild() on objects in ReplicatedStorage from the Server futile? It never really made sense to me as to why people call :WaitForChild() on modules / models in ReplicatedStorage from the Server when referencing objects directly is faster? This is a benchmark I did with @VerdommeManDevAcc’s Benchmarking Module:

Function1 and Function2 represent these:

function function1()
    local Module = require(game:GetService("ReplicatedStorage"):WaitForChild("ModuleScript"))
end

function function2()
    local Module = require(game:GetService("ReplicatedStorage").ModuleScript)
end

Hey!

As far as I’m concerned, you are right, there is not point really to thoughtlessly use :WaitForChild(). The method itself is a yielding function, but behaves similarly to :FindFirstChild() if the object already exists, talking about speed of course, not return values (unless it has been changed recently, which is unlikely).

Logically speaking, server doesn’t need to wait for instances in ReplicatedStorage, because they are available right from the start.

Direct indexing is faster, but such time delta is negligible, so the advantage of using direct paths is in shortness and readability.

3 Likes

Once game.Loaded fires (or game:IsLoaded() returns true), the client can assume all objects in ReplicatedStorage that were there when the player entered the server are available. LocalScripts run after the game is loaded (except for within ReplicatedFirst).

Thus, a LocalScript does not need to use WaitForChild for ReplicatedStorage objects unless the LocalScript is in ReplicatedFirst or the items may have been added to ReplicatedStorage by a server-side script after the player may have entered the game.

11 Likes

WaitForChild() is used when the targetted resource potentially isn’t loaded in yet. It allows you to reference an Instance without causing errors in the script. A good example use of this is with PlayerGui.

Say you have a script is executed when the game starts, that references something in PlayerGui. Referencing the PlayerGui directly will cause an error as 9 times out of 10, it hasn’t loaded in yet. So instead we use WaitForChild() which keeps checking whether the instance exists or not.

So to answer your question: Its used to reference instances that possibly don’t exist. However using it for ReplicatedStorage, like you and @EssenceExplorer both said, is a bit pointless.

2 Likes