Game lags after many inputs (?)

The Problem.

My game lags a lot after many inputs. Whether it be outside of roblox or inside of roblox.
The lag happens when a player presses a button which freezes the game a little before continuing as usual. This doesn’t happen again if the player is holding the button after the lag happens.

Why Does This Happen?

After looking at another game, I realized that the lag similar to mine happened too. I instantly knew it was UIS (User Input Service) causing all of this. Since UIS.InputBegan as described, triggers when an input is pressed, which means that it checks for EVERY. SINGLE. INPUT. waiting and waiting until the correct key is pressed.

Now, I don’t know a solution to this since I’m good at coding just not the best (like no one ever was). So I’m reaching out to open-minded people to help me with this.

:warning: I AM NOT AN EXPERT IN RLUA SO TAKE THIS WITH A GRAIN OF SALT :warning:

(god, this sounds like a youtube video.)

Do you have code to provide us? You most likely have a major memory leak.

All I can say is that I have a lot of scripts that have UIS in them.
But memory leak is new to me could you tell me more about it?

Basically a memory leak is when you dont clean up after yourself, imagine having a lava part and tying it to something like this

LavaPart.Touched:Connect(function(hitPart)
 local humanoid = hitPart.Parent:FindFirstChildOfClass("Humanoid")
 if humanoid then
  humanoid:TakeDamage(100)
 end
end)
task.wait(5)
LavaPart:Destroy()

Even though you are destroying LavaPart the connection is still tied to that function, in order to fix this you can create a local variable for the connection

local connection = LavaPart.Touched:Connect(function(hitPart)
 local humanoid = hitPart.Parent:FindFirstChildOfClass("Humanoid")
 if humanoid then
  humanoid:TakeDamage(100)
 end
end)
task.wait(5)
connection:Disconnect() -- Disconnects the function
connection = nil -- Sets to nil so the variable doesnt exist anymore
LavaPart:Destroy()

This is just a very basic memory leak which over time if scaled it can result in bigger issues in your game. Assuming you have multiple UIS that could be a memory leak. Try and put them all into one local script and see if that fixes your issue. I am not entirely sure if it could be a memory leak or not but try and do that and let me know how it goes.

1 Like

All connections tied to an instance that has the destroy method called on it will be disconnected.

Edit: Holding a strong reference to a destroyed instance however will cause a memory leak.

Example:

local T = {Part}
Part:Destroy()

print(T) -- Will show the part is still in the table and it wont get garbage collected 

4 Likes

Doesn’t this mean that EVERY. SINGLE. SCRIPT. is trying to execute at the same time?

Wouldn’t that cause a lot of problems?

Why do you have “a lot” of scripts with UIS?