PSA: Yielding in RBXScriptConnection Callbacks may Disable some Optimizations

This one will be a quicky, but something I realized that callback threads tend to do for RBXScriptConnections is that they will reuse the same thread when applicable. This helps save performance by not having to recreate a new thread every invocation and thus levying the overall GC load.

local Last

local function OnPreAnimation()
	local Current = coroutine.running()
	
	-- always true after initial invocation
	print(Current == Last)
	Last = Current
end

RunService.PreAnimation:Connect(OnPreAnimation)

However, this optimization won’t work if the callback yields, because the previous thread still needs to be used for when the last invocation resumes.

local Last

local function OnPreAnimation()
	local Current = coroutine.running()
	
	-- now always false
	print(Current == Last)
	Last = Current
	
	-- yielding!
	task.wait()
end

RunService.PreAnimation:Connect(OnPreAnimation)

Many of you might also know that this is the same optimization used for stravant’s GoodSignal implementation, and so the same rules for it also apply.

5 Likes