GetPlayers() VS caching players in a table

Method 1:

while true do
    task.wait(0.25)
    
    for _, plr in pairs (Players:GetPlayers()) do
        -- do thing on player
    end
end

Method 2:

local playerCache = {}

Players.PlayerAdded:Connect(function(plr)
    table.insert(playerCache, plr)
end)

while true do
    task.wait(0.25)
    
    for _, player in pairs (playerCache) do
        -- do thing on player
    end
end

Which is more performant?
At maximum, there will be 20 players.
For method 2, I can replace the in pairs loop with a for i loop.

1 Like

method 1 because it’s easy to use (for me)

They both run the same performance-wise. Using the cache not only makes you required player added connections but also brings in a lot of unnessecary code. Use :GetPlayers().

I don’t think there’s the “right” way to do it, That’s more likely a personal thing. But if i were to use one, I would use :GetPlayers().


That’s really up to you, As if you really care alot about the order which the Players are being looped through, You can use ipairs(). Most people use the Cache thing since it avoids memory leaks.