My friend has this code and in my opinion it has way too many for loops and just generally looks really unoptimized, so I’m posting this here for him.
“It’s supposed to be a squad system, and it teleports players in a certain squad(which is a folder in the workspace) to teleport to a certain server” - My friend
If you know anyway to make this code better please tell us.
If you have any questions about the code, reply to this thread so I can ask my friend and reply back to you.
2 Likes
When you’re talking about optimizing your code, I assume you are meaning making it faster. Two ways I could think of is change pairs
to ipairs
as ipairs
is generally faster than pairs
. Another change I’d do is declare TS outside of the function.
Although this system probably isn’t too slow, you have two major things you can do to optimize it for code readability and performance.
- Use
FindFirstChild
instead of running loops through the children and doing name comparisons. - Currently, you are calling
TeleportToPrivateServer
for each individual player in the list instead of teleporting them all at once after you make a table of players to teleport.
Optimized code:
local teleport = game:GetService("TeleportService")
local players = game:GetService("Players")
function Squad:Start(folderForSquads, player, id)
local folder = folderForSquads:FindFirstChild(player.Name)
local playersToTeleport = {}
-- Create list of players to teleport
for _, value in folder:GetChildren() do
local playerToTeleport = players:FindFirstChild(value.Name)
if playerToTeleport then
table.insert(playersToTeleport, playerToTeleport)
end
end
-- Teleport all players to private server
pcall(function()
local accessCode = teleport:ReserveServer(id)
teleport:TeleportToPrivateServer(id, accessCode, playersToTeleport)
end)
end
1 Like