What's the most optimal way to check alot of units (800+) distance from eachother?

I’m making an RTS game and I’ve run into a big issue. While my previous sorting issue was fixed using table.sort, if I add a lot of units (obviously accounting for end-game unit production), there is server lag of up to 1000 MS. Now while this is something that unfortunately plagues many Roblox RTS games, I’m seeking to find a way to stop this issue.

The way it works right now is I run two nested index, value loops in a while true do and I check the magnitude of both. There is a table.sort to sort the table that the i,v loops cycle through based off compared magnitude.

However, it’s pretty clear that looping through 800 units and checking their magnitude is not optimized. I heard something about GetPartsBoundInRadius, but I’m not sure if this will be more or less optimized than my current implementation, which again uses two nested I,V loops and a while true do loop (written below)

local UnitsTable = {}
local Units = game.Workspace.InitializedUnits:GetChildren()
for _, unit in ipairs(Units) do
	if not table.find(UnitsTable, unit) then 
		table.insert(UnitsTable, unit)
	end
end

while true do
	for _, Unit in ipairs(UnitsTable) do
		table.sort(UnitsTable, function(unitA, unitB)
			return
				Unit and Unit.PrimaryPart and unitA and unitA.PrimaryPart and unitB and unitB.PrimaryPart 
				and unitA:GetAttribute("Team") ~= Unit:GetAttribute("Team") and
				(unitA.PrimaryPart.Position - Unit.PrimaryPart.Position).Magnitude < (unitB.PrimaryPart.Position - Unit.PrimaryPart.Position).Magnitude
		end)
		for _, Target in ipairs(UnitsTable) do
			if Unit.PrimaryPart and Unit.PrimaryPart.Position and Target.PrimaryPart and Target.PrimaryPart.Position and
				Target:GetAttribute("Team") ~= Unit:GetAttribute("Team") and (Target.PrimaryPart.Position - Unit.PrimaryPart.Position).Magnitude < 10 then
				print("IWillKill", Target)
				Target:Destroy()
				table.remove(UnitsTable, table.find(UnitsTable, Target))
			end
		end
	end
	task.wait(0.2)
end

Id look into spatial partioning, such as Octrees or Quadtrees.