Script uses a lot of activity despite only waiting?

I can’t for some reason find why this script has a lot of activity despite the most performance heavy thing I see is the while loop which is conditional and breaks

if not Table[plr.Name] then
		Table[plr.Name] = tick()
		plr.Data.InCombat.Value = true
		coroutine.wrap(function()
			while tick() - Table[plr.Name] < 30 and plr.Character.Humanoid.Health > 0 and plr.Character:IsDescendantOf(game) do
				RService.Heartbeat:Wait()				
			end
			if plr.Character:IsDescendantOf(game)then
				plr.Data.InCombat.Value = false
			end
			Table[plr.Name] = nil	
		end)()
	else
		Table[plr.Name] = tick()
	end```

The main problem is this. You’re checking the tick for what I presume is 30 seconds every single frame. And not only checking tick, but Health and is Player:IsDescendantOf(), which is decently expensive function. And if this is on the server, its doing that more multiple people at once.

Realistically, you should only be checking maybe once per second, not roughly 60 times per second. You can also ease the amount of times you check health and the players existence with listener functions.

if not Table[plr.Name] then
	Table[plr.Name] = tick()
	plr.Data.InCombat.Value = true
	local listenDeath, listenLeave
	listenDeath = plr.Character.Humanoid.Died:Connect(function()
		plr.Data.InCombat.Value = false
	end)
	listenLeave = plr.AncestryChanged:Connect(function()
		if not plr:IsDescendantOf(game) then
			plr.Data.InCombat.Value = false
		end
	end)
	
	local count = 0
	while count < 30 do
		if not plr.Data.InCombat.Value then
			return
		end
		wait(1)
		count = count + 1
	end
	listenDeath:Disconnect() -- prevent memory leaks
	listenLeave:Disconnect()
	
	Table[plr.Name] = nil	
else
	Table[plr.Name] = tick()
end


1 Like

Ah I see, thank you but this means I’d have to connect and disconnect events in rapid succession, wouldn’t this like lead to performance issues?

It’s far less expensive than checking the players status tens of times a second. And you won’t necessarily be “rapidly” disconnecting events, it would only be every 30 seconds or so unless the player dies/leaves before that.

Ok thanks, I guess the problem most people have with while loops is the rate it loops thanks

yup, it was the rate it was checking my if statements, it decreased my activity and rate by a ton, tysm

1 Like

I do have a minor question however, say I have to connect and disconnect events every 0.5 seconds, will this cause a problem with performance?

I’m not sure how expensive disconnecting events are because I’ve never had to rapidly connect/disconnect something. I imagine it’s not a great thing to do though, and I’m not sure what your use case for this is?

However, I looked at the wiki and realized that you actually don’t need to disconnect these events as the player respawning/leaving will automatically disconnect the events for you.