Player search optimization

I am trying to make a player search for my game but I am facing a big problem of optimization. I create instances and destroy them a lot of times and have no idea what’s the alternative

Code:

local Player_Button = script:WaitForChild("TextButton")

local List = script.Parent:WaitForChild("ScrollingFrame")

local TextBox = script.Parent:WaitForChild("TextBox")
local Player_Service = game:GetService("Players")

local function update(str)
    local Players = Player_Service:GetChildren()
    
    for _,child in (List:GetChildren()) do
        child:Destroy()
    end
    
    for _,plr in (Players) do
        local match = string.match(plr.Name,str)
        if match then
            local C = Player_Button:Clone()
            C.Parent = List
            C.Text = plr.Name
        end
    end
    
end
    
update("")

TextBox:GetPropertyChangedSignal("Text"):Connect(function()
    update(TextBox.Text)
end)

https://gyazo.com/c8afabd4441bc8c7eaf0fe4a181977f2

You can make an independent function that creates or removes instances according to the current, joined, and left players, and then make those instances visible to the search respectfully. That way, the instances won’t be created every time the player does a search, and will only be updated when a player joins or leaves.

2 Likes