How could I optimize this?

Hi,

I have this clientszide code:



local localPlayerPos = localPlayer:GetPos()
local players = player.GetAll()

table.sort( players,
    function( a, b )
        return (b:GetPos():Distance( localPlayerPos ) < a:GetPos():Distance( localPlayerPos ))
    end
)
		
for _, ply in ipairs( players ) do
    local pos = ply:GetPos()
    local distance = pos:Distance( localPlayerPos )
    ....


I would like to optimize it so that I would not need to re-get the pos and recalculate the distance in the for loop. Since I already get the pos and calculate the distances in the sorting function, I believe there is a way to store them somewhere so that I could just reuse this stored value in the loop.

I believe there is a function, which I can’t remember, that allow to set and get additional informations to/from a player’s table…or something like that :slight_smile:

Any idea ?

Player.VariableName = value

Can you give us a background as to what you’re using that for and how often you’re calling it?

There may be an easier way, there may not be; we won’t know unless you give us a bit more information!

The script draws a text above players and it draws the closest player first and the farthest last. It’s called in a HUDPaint hook, so quite often.

Everything is working well, now I try to optimize the speed as much as I can… :slight_smile:

Edit: following Kuro Light’s advice, I’ve made this:



table.sort( players,
    function( a, b )
        a.Pos = a:GetPos()
        a.Dist = a.Pos:Distance( localPlayerPos )
        b.Pos = b:GetPos()
        b.Dist = b.Pos:Distance( localPlayerPos )
        return (b.Dist < a.Dist)
    end
)


And I can use ply.Pos and ply.Dist in the for loop. I completely forgot we could do this. I’m always overthinking :slight_smile:

I don’t think there is a better way than this. Right?



local localPlayerPos = Vector()

local function sortplayers( a, b )
	return b.TempDistance < a.TempDistance
end

function GM:HUDPaint()
	localPlayerPos = EyePos()
	local players = player.GetAll()

	for _, ply in pairs(players) do
		ply.TempDistance = ply:GetPos():Distance(localPlayerPos)
	end

	table.sort( players, sortplayers )

	for _, ply in ipairs( players ) do
	    local pos = ply:GetPos()
	    local distance = ply.TempDistance


this is really a micro optimization but if you only need to compare distances you can use Vector:DistToSqr(), it gives the distance squared so it saves a square root operation