```lua
local cachedLP

local function LP()
    local lp = cachedLP
    if not IsValid(lp) then
        lp = LocalPlayer()
        cachedLP = lp
    end
    return lp
end

-- hot path
local lp = LP()
if IsValid(lp) then
    -- reuse lp here instead of calling LocalPlayer() repeatedly
end
```
Reason: cache the entity in a local upvalue and only refresh it when the cached value is missing or invalid, which avoids repeated global lookup and repeated engine calls on hot paths.


```lua
local function ArePlayersRoughlyLookingAtEachOther(plyA, plyB, dotThreshold)
    dotThreshold = dotThreshold or 0.8 -- higher = stricter cone

    if not IsValid(plyA) or not IsValid(plyB) then return false end

    local aToB = (plyB:EyePos() - plyA:EyePos()):GetNormalized()
    local bToA = -aToB

    return plyA:GetAimVector():Dot(aToB) >= dotThreshold
       and plyB:GetAimVector():Dot(bToA) >= dotThreshold
end
```
Reason: Dot products give a cheap cone test for “roughly facing” without the extra cost of `math.acos`.


```lua
SomeHelper(ply)
```
Reason: a direct function call avoids method-call sugar and is generally a bit cheaper than `ply:SomeHelper()` for a helper you control.


```lua
MsgN("hot path debug")
```
Reason: `MsgN` writes directly to the console and skips `print`'s extra formatting work, so it is cheaper in a hot path.


```lua
local t = numbers
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: Numeric `for` is usually fastest for a dense sequential array because it avoids the iterator overhead of `pairs`/`ipairs` and gives direct indexed access.


```lua
local function aliveNamesByJob(players, jobId)
    local out, n = {}, 0

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:Alive() and ply:Team() == jobId then
            n = n + 1
            out[n] = ply:Nick()
        end
    end

    return out
end

-- Example:
-- local names = aliveNamesByJob(player.GetAll(), TEAM_POLICE)
```
Reason: One numeric loop with no combinator chaining, no intermediate tables, and no extra closure dispatch does the same filter+map work with less overhead.


```lua
local cachedPlayers = player.GetAll()

local function RefreshPlayerCache()
    cachedPlayers = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "MyAddon.RefreshPlayerCache", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "MyAddon.RefreshPlayerCache", RefreshPlayerCache)

hook.Add("Think", "MyAddon.PlayerLoop", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- fast per-player work here
        end
    end
end)
```
Reason: It avoids allocating and traversing a fresh `player.GetAll()` table every tick by reusing a cached list and rebuilding it only when the player list changes.


```lua
local pdata = setmetatable({}, { __mode = "k" }) -- weak keys auto-drop when the player entity is gone

local function GetPData(ply)
    local t = pdata[ply]
    if not t then
        t = {}
        pdata[ply] = t
    end
    return t
end

-- write once
GetPData(ply).myField = value

-- read often
local data = pdata[ply]
if data then
    local v = data.myField
end
```
Reason: `ply.someField` is replaced by a plain table lookup in a module-local cache, and caching `pdata[ply]` in a local makes repeated reads cheaper while avoiding per-entity field mutation.


```lua
local values = {
    "alpha",
    "beta",
    "gamma",
}

for i = 1, #values do
    local v = values[i]
    -- use v
end
```
Reason: Sequential number-indexed arrays are faster to iterate in Lua than string-keyed maps because they support dense, cache-friendly numeric traversal with less lookup overhead.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing raw RGBA numbers avoids constructing or unpacking a `Color` table on every draw, which is the cheaper hot-path call.


```lua
local rows = sql.Query("SELECT value FROM playerdata WHERE steamid64 = " .. sql.SQLStr(steamid64))
```
Reason: For one Garry's Mod server with no sync requirement, local SQLite is typically lower latency because it avoids network round trips and uses an embedded on-disk database.


```lua
local steamid_cache = setmetatable({}, { __mode = "k" })

local function SteamIDCached(ply)
    local steamid = steamid_cache[ply]
    if steamid == nil then
        steamid = ply:SteamID()
        steamid_cache[ply] = steamid
    end
    return steamid
end

-- Hot path use:
-- local sid = SteamIDCached(ply)
```
Reason: Caches each player's immutable SteamID once per entity, avoiding repeated method calls on the hot path while keeping entries eligible for garbage collection.


Answer must contain 0 through 0 candidate loops.

```lua
local parts = {}
local n = 0

for i = 1, 10000 do
    n = n + 1
    parts[n] = "piece" .. i
end

local result = table.concat(parts)
```
Reason: `table.concat` builds the final string in one pass, while repeated `..` creates many intermediate strings and gets slower as the number of pieces grows.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, so it avoids the extra rounded-box path and is a bit cheaper for repeated solid-rect rendering.


```lua
-- cache the font name outside the hot path if you can
local fontName = "DermaDefault"

hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont(fontName)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText("Single-line text")
end)
```
Reason: `surface.DrawText` with a preselected font is the lightest per-frame path for plain one-line text; it avoids the extra alignment, sizing, and outline work in `draw.DrawText` and `draw.SimpleTextOutlined`.


```lua
local n = #myTable
```
Reason: `#` is the preferred operator for sequential array-like tables in Lua; `table.Count` is for generic tables, not arrays.


```lua
t = {}
```
Reason: Rebinding to a new table is generally faster for discarding a large table because it avoids clearing every element; use `table.Empty(t)` only when other references must see the same table emptied.


```lua
local allowed = {
    ["weapon_pistol"] = true,
    ["weapon_smg1"] = true,
    ["weapon_ar2"] = true,
}

if allowed[weaponClass] then
    -- exists in set
end
```
Reason: A keyed lookup in a set-style table is O(1) average time, while `table.HasValue` scans the list linearly.


```lua
-- Faster for a small table with known fields
local t = {
    x = 1,
    y = 2,
    z = 3,
}

-- Slower: create first, then assign fields
-- local t = {}
-- t.x = 1
-- t.y = 2
-- t.z = 3
```
Reason: the table constructor builds the table with its fields in one step, so it avoids separate assignments and is typically faster.


```lua
local function RandomSequential(t)
    return t[math.random(#t)]
end
```
Reason: It picks a random index directly in O(1) instead of scanning the table like `table.Random`.


```lua
local xx = x * x
```
Reason: `x * x` is the simplest and fastest way to square a number in a tight Lua loop; it avoids the overhead of `^` or `math.pow`.


Uses ipairs but still allocates via player.GetAll() each time.

```lua
for _, ply in ipairs(player.GetAll()) do
    -- ply is each currently connected player
end
```
Reason: `player.GetAll()` returns the current connected players as an array, so `ipairs` is the matching loop for visiting each one in order.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process ent here
end
```
Reason: `ents.FindByClass` returns only `prop_physics` entities, so you avoid building a table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a callback for the `Think` hook, and `MyAddon.Think` is the identifier used to name that callback.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:Remove() -- or any other method call
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod guard for nil, NULL, or deleted entities before calling methods on them.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming data here
end)
```
Reason: This registers a callback that runs whenever the `MyAddon.Sync` net message is received.


```lua
local ZERO_ANGLE = angle_zero

-- hot path
local ang = ZERO_ANGLE
```
Reason: `angle_zero` is preallocated and zeroed, so you avoid constructing a new `Angle()` each time.


```lua
local addon_color = Color(255, 0, 0)
local c = addon_color
```
Reason: A local/upvalue is the fastest read path in Lua because it avoids repeated table lookups; `myaddon.config.color` costs extra indexing, and globals are slower than locals.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP exposes the job name as a DarkRPVar, so `getDarkRPVar("job")` is the supported accessor; `GetNWString("job")` reaches into the raw networked string directly.


```lua
if pos1:DistToSqr(pos2) <= maxDist * maxDist then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root and is the preferred way to do a vector threshold check.


```lua
for _, ent in ents.Iterator() do
    -- visit ent here
end
```
Reason: `ents.Iterator()` walks entities without building the full `ents.GetAll()` table, so it is the efficient choice for a simple visit-each-entity loop.


```lua
local pos = ply:GetPos()
local nearby = ents.FindInSphere(pos, 256)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query and is a common benchmark winner for simple nearby-entity lookups without the heavier cost of `FindInPVS`.


```lua
local function PlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local result = {}

    for _, ply in ipairs(player.GetAll()) do
        if ply:Alive() and ply:GetPos():DistToSqr(pos) <= radiusSqr then
            result[#result + 1] = ply
        end
    end

    return result
end
```
Reason: `player.GetAll()` iterates only players, so it skips every non-player entity that `ents.FindInSphere` would scan, and `DistToSqr` avoids the square-root cost.


```lua
for i = 1, n do
  -- tight counting loop
end
```
Reason: A numeric `for` loop is generally faster than a `while` loop for simple counting in Garry's Mod Lua because it has lower per-iteration overhead.


```lua
hook.Add("Tick", "NotifyPlayersOnce", function()
    local players = player.GetAll()
    hook.Run("MyAddon_PlayerTickBatch", players)
end)

hook.Add("MyAddon_PlayerTickBatch", "MyAddon_Logic", function(players)
    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) then
            -- per-player custom logic here
        end
    end
end)

-- slower pattern:
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("MyAddon_PlayerTick", ply)
-- end
```
Reason: one hook dispatch plus one player-list pass is cheaper than calling hook.Run once per player, because hook.Run has fixed overhead on every call.


```lua
hook.Add("HUDPaint", "Example", function()
    local lp = LocalPlayer()
    local hp = lp:Health()

    draw.SimpleText(hp, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(hp, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(hp, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache the player and health once per frame so the hook avoids repeating the same lookup and method call three times.


```lua
local WHITE = color_white

hook.Add("HUDPaint", "MyPaint", function()
    for i = 1, 100 do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(i, 10, 8, 8)
    end
end)
```
Reason: `Color(255,255,255)` allocates a new color table every call; caching `color_white` (or one `Color(...)` created once) removes per-iteration allocation and GC churn.


```lua
local sin = math.sin

for i = 1, n do
  sum = sum + sin(values[i])
end
```
Reason: `sin` is bound once, so the hot loop avoids repeated `math.sin` table lookups and uses a cheaper local access.


```lua
local LocalPlayer = LocalPlayer
local cachedLP

hook.Add("Think", "CacheLocalPlayer", function()
    cachedLP = LocalPlayer()
end)

hook.Add("HUDPaint", "UseCachedLocalPlayer", function()
    local lp = cachedLP
    if not IsValid(lp) then return end

    -- use lp here instead of calling LocalPlayer() repeatedly
end)
```
Reason: cache the function and the returned player entity, then reuse the local in hot paths so you avoid repeated global lookups and repeated LocalPlayer() calls.


```lua
local function ArePlayersRoughlyFacingEachOther(plyA, plyB, dotThreshold)
    if not IsValid(plyA) or not IsValid(plyB) then return false end

    dotThreshold = dotThreshold or 0.85 -- lower = wider cone

    local aToB = (plyB:EyePos() - plyA:EyePos()):GetNormalized()
    local bToA = -aToB

    return plyA:GetAimVector():Dot(aToB) >= dotThreshold
       and plyB:GetAimVector():Dot(bToA) >= dotThreshold
end
```
Reason: Dot products are cheap and compare direction directly, so this avoids the extra cost of computing an angle with `math.acos`.


```lua
SomeHelper(ply)
```
Reason: A plain function call avoids method lookup and implicit `self` passing, so it is generally a bit faster than `ply:SomeHelper()` for a helper you control.


```lua
MsgN("[debug] health=", health, " pos=", pos)
```
Reason: `MsgN` writes straight to the console with less formatting overhead than `print`, so it is the cheaper choice in a hot path.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: A numeric `for` avoids iterator overhead and is typically the fastest choice for dense sequential tables; `ipairs` is usually slower, and `pairs` is the slowest.


```lua
-- Replaces fn.Filter(...) + fn.Map(...) with one pass.
local function activePlayerNames(players)
    local out = {}
    local n = 0
    local isValid = IsValid
    local spectator = TEAM_SPECTATOR

    for i = 1, #players do
        local ply = players[i]
        if isValid(ply) and ply:Alive() and ply:Team() ~= spectator then
            n = n + 1
            out[n] = ply:Nick()
        end
    end

    return out
end
```
Reason: one numeric `for` loop fuses filter and map, avoids intermediate tables and combinator dispatch, and keeps output packed with `out[n] = ...`.


```lua
local cachedPlayers = player.GetAll()

local function RefreshCachedPlayers()
    cachedPlayers = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "RefreshCachedPlayers", RefreshCachedPlayers)
hook.Add("PlayerDisconnected", "RefreshCachedPlayers", RefreshCachedPlayers)

hook.Add("Tick", "MyPlayerLoop", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- work here
        end
    end
end)
```
Reason: `player.GetAll()` allocates and scans every call; caching the table and refreshing only on join/leave removes that per-tick cost.


```lua
local values = {
    "alpha",
    "beta",
    "gamma",
}

for i = 1, #values do
    local v = values[i]
    print(v)
end
```
Reason: Sequential number-indexed arrays use Lua's array part and avoid hash lookup overhead, so they iterate faster than string-keyed maps.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Separate numeric channels are the faster hot-path call because they avoid the Color object path.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = " .. SQLStr(steamid))
```
Reason: Local SQLite is typically lower latency for a single Garry's Mod server because it avoids network round trips and runs in-process.


```lua
local steamid_cache = setmetatable({}, { __mode = "k" })

local function GetSteamIDCached(ply)
    local sid = steamid_cache[ply]
    if sid == nil then
        sid = ply:SteamID()
        steamid_cache[ply] = sid
    end
    return sid
end

-- hot path
for i = 1, #players do
    local ply = players[i]
    local sid = GetSteamIDCached(ply)
    -- use sid here
end
```
Reason: It turns repeated method calls into one lookup per player, and the weak-key cache avoids leaking entries after players disappear.


```lua
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece" .. i
end

local result = table.concat(parts)
```
Reason: `table.concat` joins the pieces in one pass, so it avoids the repeated reallocations and full-string copies caused by `..` inside a loop.


```lua
surface.SetDrawColor(col)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips the rounded-box path and draws a plain rectangle directly, so it has a bit less overhead than `draw.RoundedBox(0, ...)`.


```lua
local font = "FastHUDText"

surface.CreateFont(font, {
    font = "Roboto",
    size = 22,
    weight = 500,
    antialias = true,
})

local text = "Single-line text"
local x, y = 50, 50

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` is the lowest-overhead path for one-line HUD text; `draw.DrawText` adds extra formatting work, and `SimpleTextOutlined` draws the glyphs multiple times for the outline.


```lua
local n = #myTable
```
Reason: `#` is the standard Lua length operator and is the preferred way to get the size of a sequential array-like table in Garry's Mod.


```lua
t = {}
```
Reason: `t = {}` is usually faster because it just rebinds the variable instead of walking the table and clearing each slot; use `table.Empty(t)` only if other references must see the same table emptied.


```lua
local allowed = {
    ["weapon_pistol"] = true,
    ["weapon_smg1"] = true,
    ["weapon_ar2"] = true,
}

if allowed[weaponClass] then
    -- exists in the set
end
```
Reason: `allowed[value]` is a direct hash lookup, while `table.HasValue` scans the list linearly.


```lua
local t = { x = 1, y = 2, z = 3 }
```
Reason: The constructor sets the fields during table creation, so it avoids the extra separate writes you do after `{}`.


```lua
local value = t[math.random(#t)]
```
Reason: `table.Random` handles any table shape, but a sequential array can be indexed directly, which avoids its extra table scanning and type handling.


```lua
x * x
```
Reason: `x * x` is the cheapest square in Lua; it avoids the extra overhead of `^` or `math.pow`.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- visit each connected player here
end
```
Reason: `player.GetAll()` returns the current player list, and `ipairs` cleanly iterates every connected player.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    if IsValid(ent) then
        -- process ent
    end
end
```
Reason: `ents.FindByClass` directly returns only matching `prop_physics` entities, so you avoid building and scanning a table of all map entities.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- minimal callback
end)
```
Reason: Use `hook.Add` with hook name `Think` and the unique identifier `MyAddon.Think` to register a callback on the Think loop.


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: Use `IsValid(ent)` which is the Garry's Mod validity check that returns false for `nil`/`NULL`/deleted entities, so calling methods inside this guard is safe.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local payload = net.ReadTable()
    -- handle payload here
end)
```
Reason: `net.Receive(messageName, callback)` is the Garry's Mod API for registering an incoming network message handler, and using `MyAddon.Sync` as the message name subscribes this function to that message.


```lua
-- one global cached zero angle provided by GMod
local ZERO_ANGLE = angle_zero

local function BorrowZeroAngle()
    return Angle(ZERO_ANGLE) -- cheaper than Angle(0, 0, 0) each call
end

local function HotPath()
    local ang = BorrowZeroAngle()
    -- use ang ...
end
```
Reason: Reusing `angle_zero` and cloning it avoids rebuilding the zeroed angle from numeric constructor args every iteration, which is the common GMod hot-path allocation optimization.


```lua
-- Faster: cache the config in a flat local once, especially for hot-path reads
local COLOR = myaddon.config.color

local r = COLOR
```
Reason: In Garry's Mod Lua, a flat local (`COLOR`) is a single upvalue access, while `myaddon.config.color` does repeated table/global lookups (hash/index chain) each time, so frequent reads are faster when stored locally.


```lua
local jobName = ply:getDarkRPVar("job") -- DarkRP job name helper
-- or, when you only have team id:
-- local jobName = team.GetName(ply:Team())
```
Reason: `GetNWString("job")` is low-level and deprecated for DarkRP job data; `getDarkRPVar("job")` (or `team.GetName(ply:Team())` using `Team()`) is the idiomatic DarkRP API and stays in sync with DarkRP’s job system.


```lua
local a = Vector(10, 20, 30)
local b = Vector(12, 22, 29)
local maxDist = 5

if a:DistToSqr(b) < (maxDist * maxDist) then
    print("Within range")
end
```
Reason: `DistToSqr` returns squared distance between two vectors, so comparing it to `maxDist^2` avoids the costly square-root in `Distance()` and is the preferred threshold check.


Answer must contain 1 through 1 candidate loops.

```lua
-- Visit every entity, using the iterator when available.
if ents.Iterator then
    for ent in ents.Iterator() do
        -- use ent
        print(ent)
    end
else
    -- Fallback for builds where ents.Iterator() is unavailable.
    for _, ent in ipairs(ents.GetAll()) do
        print(ent)
    end
end
```
Reason: ents.Iterator is the wiki-recommended lightweight entity iterator when present, with ents.GetAll() as a compatibility fallback.


```lua
local function FindNearbyEntitiesCheap(ply, radius)
    local origin = ply:GetPos()
    local r = radius or 256
    local ext = Vector(r, r, r)
    local candidates = ents.FindInBox(origin - ext, origin + ext)

    local r2 = r * r
    local out = {}

    for i = 1, #candidates do
        local ent = candidates[i]
        if ent ~= ply and IsValid(ent) and origin:DistToSqr(ent:GetPos()) <= r2 then
            out[#out + 1] = ent
        end
    end

    return out
end
```
Reason: `ents.FindInBox` is a fast built-in broad-phase spatial query; filtering with `DistToSqr` avoids expensive sqrt while keeping the result bounded near the player without using `FindInPVS`.


```lua
-- Server-side: check only players, avoid ents.FindInSphere + class filtering
local function GetPlayersInRadius(pos, radius, includeBots)
    local radiusSqr = radius * radius
    local result = {}

    for _, ply in ipairs(player.GetAll()) do
        if IsValid(ply)
            and (includeBots or not ply:IsBot())
            and ply:GetPos():DistToSqr(pos) <= radiusSqr then
            result[#result + 1] = ply
        end
    end

    return result
end

-- Example
local origin = Vector(100, 200, 300)
local nearby = GetPlayersInRadius(origin, 500)
for i = 1, #nearby do
    local ply = nearby[i]
    -- do work for each nearby player
end
```
Reason: Iterating `player.GetAll()` and doing `DistToSqr` checks limits work to player entities only, avoids allocating and traversing all entities from `ents.FindInSphere`, and avoids expensive square-root distance calls.


```lua
local i = 1
local n = 1000000
local count = 0

while i <= n do
    count = count + 1
    i = i + 1
end
```
Reason: In Garry's Mod Lua, a tight counting loop is typically faster with a manual `while` loop (`local i = 1; while i <= n do ...; i = i + 1 end`) because it uses the minimal increment-and-compare path without numeric-for loop overhead.


```lua
-- Faster: one hook dispatch per tick, not one per player.
local hookName = "CustomPlayersTick"

hook.Add("Think", "NotifyPlayersTick_Forwarder", function()
    local players = player.GetHumans() -- or player.GetAll()
    hook.Run(hookName, players, CurTime())
end)

hook.Add(hookName, "HandleAllPlayersTick", function(players, now)
    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) then
            -- custom logic for this player
        end
    end
end)
```
Reason: Dispatching `hook.Run` once per tick is faster because it reduces hook lookup/call overhead from N times to 1 and lets one listener handle the player loop in a single pass.


```lua
hook.Add("HUDPaint", "FastHealthHUD", function()
    local lp = LocalPlayer()
    if not IsValid(lp) then return end

    local health = lp:Health() -- single fetch this frame
    local txt = "Health: " .. health
    local barW = math.Clamp(health, 0, 100) * 2

    draw.SimpleText(txt, "DermaDefault", 16, 16, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText(("HP: %d"):format(health), "DermaDefault", 16, 34, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.RoundedBox(0, 16, 58, barW, 12, Color(220, 40, 40, 220))
end)
```
Reason: Cache `LocalPlayer()` and `Health()` once, then reuse the `health` value across all three HUD draw calls, avoiding repeated cross-boundary calls in the same frame.


```lua
local WHITE_R, WHITE_G, WHITE_B, WHITE_A = 255, 255, 255, 255

hook.Add("HUDPaint", "FastPaintLoop", function()
    local t = items
    local n = #t
    if n == 0 then return end

    -- set color once, reused for every draw call in the loop
    surface.SetDrawColor(WHITE_R, WHITE_G, WHITE_B, WHITE_A)

    for i = 1, n do
        local itm = t[i]
        surface.DrawRect(itm.x, itm.y, itm.w, itm.h)
    end
end)
```
Reason: Calling `Color(...)` inside the hot loop allocates per-iteration color data, while caching numeric components (or the color) once and reusing `surface.SetDrawColor` removes repeated allocations and lowers per-frame overhead.


```lua
local sin = math.sin -- cache lookup once

for i = 1, 1000000 do
    local v = sin(i * 0.1)
    -- use v ...
end
```
Reason: Lua resolves globals each call, so caching `math.sin` in a local variable turns one table lookup into one-time setup and makes each loop call a fast local upvalue access.


```lua
-- cache.lua
local lp

local function refreshLocalPlayer()
    local p = LocalPlayer()
    if IsValid(p) then
        lp = p
    end
end

-- one-time setup when client is ready
hook.Add("InitPostEntity", "CacheLocalPlayer", refreshLocalPlayer)

-- safety: player can be nil briefly; repair lazily
local function getLocalPlayer()
    if not IsValid(lp) then
        refreshLocalPlayer()
    end
    return lp
end

-- hot path usage
hook.Add("Think", "MyAddon_Think", function()
    local ply = getLocalPlayer()
    if not IsValid(ply) then return end

    -- fast path: use `ply` for the rest of this frame
    -- ply:SetNWBool(...)
end)
```
Reason: Cache `LocalPlayer()` in a local upvalue and only re-resolve when invalid instead of calling it repeatedly in hot loops.


```lua
local function AreMutuallyLooking(p1, p2, cosHalfFov, maxDistSq)
    local p1Pos = p1:EyePos()
    local p2Pos = p2:EyePos()

    local toP2 = p2Pos - p1Pos
    local distSq = toP2:LengthSqr()
    if distSq <= 0 or (maxDistSq and distSq > maxDistSq) then return false end

    local dir = toP2:GetNormalized() -- direction from p1 to p2
    local p1Dir = p1:GetAimVector()
    local p2Dir = p2:GetAimVector()

    return p1Dir:Dot(dir) >= cosHalfFov and p2Dir:Dot(-dir) >= cosHalfFov
end

-- Example: ~30° cone each (cos(15°)) and optional distance cap at 1500u
-- local c = math.cos(math.rad(15))
-- local closeSq = 1500^2
-- if AreMutuallyLooking(plyA, plyB, c, closeSq) then ... end
```
Reason: Use unit vectors and a single dot-product comparison (against a precomputed cosine threshold) so you avoid acos/angle math and extra trig work while still getting an O(1) mutual-aim check.


```lua
local function SomeHelper(ply)
    -- fast-path helper code
end

local result = SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is usually marginally faster or equal for helper-owned functions because colon syntax is pure syntax sugar that also performs method lookup on `ply` (`ply:SomeHelper(...)`), so passing `ply` explicitly avoids extra dispatch overhead and is clearer in hot paths.


```lua
-- Faster than print() in a hot path
Msg("[DBG] value=", value, "\n")
```
Reason: `Msg` writes directly to the console and avoids `print`'s multi-arg tostring/formatting and extra debug overhead in Garry's Mod Lua.


```lua
local nums = {10, 20, 30, 40, 50}
local total = 0

local n = #nums -- cache once for the loop
for i = 1, n do
    total = total + nums[i]
end

print(total)
```
Reason: For a dense 1..n array in Lua, numeric `for` with direct index access is the fastest and most predictable; `pairs` and `ipairs` add iterator overhead and slower dispatch.


```lua
local function richAliveNicknames()
    local result = {}
    local n = 0

    for i = 1, #player.GetAll() do
        local ply = player.GetAll()[i]

        if IsValid(ply) and ply:Alive() and ply.getDarkRPVar then
            local wallet = ply:getDarkRPVar("money")
            if wallet and wallet >= 5000 then
                n = n + 1
                result[n] = ply:Nick()
            end
        end
    end

    return result
end

local rich = richAliveNicknames()
-- use rich
```
Reason: This fuses filter+map into one pass with a plain numeric loop, avoiding DarkRP fn’s iterator/closure overhead and avoiding extra intermediate tables from separate filter/map stages.


```lua
local cachedPlayers = {}
local playerIndex = {}

local function rebuildCache()
    table.Empty(cachedPlayers)
    table.Empty(playerIndex)

    local all = player.GetAll()
    for i = 1, #all do
        local ply = all[i]
        cachedPlayers[i] = ply
        playerIndex[ply] = i
    end
end

local function addPlayer(ply)
    if playerIndex[ply] or not IsValid(ply) then return end

    local idx = #cachedPlayers + 1
    cachedPlayers[idx] = ply
    playerIndex[ply] = idx
end

local function removePlayer(ply)
    local idx = playerIndex[ply]
    if not idx then return end

    local lastIdx = #cachedPlayers
    local lastPly = cachedPlayers[lastIdx]

    cachedPlayers[idx] = lastPly
    playerIndex[lastPly] = idx

    cachedPlayers[lastIdx] = nil
    playerIndex[ply] = nil
end

hook.Add("Initialize", "PlayerCache_Init", rebuildCache)
hook.Add("PlayerInitialSpawn", "PlayerCache_Add", addPlayer)
hook.Add("PlayerDisconnected", "PlayerCache_Remove", removePlayer)

hook.Add("Think", "MyFastThink", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- per-tick logic here
    end
end)
```
Reason: This removes `player.GetAll()` from the tick path and keeps a live cache updated only on join/leave hooks, so each tick iterates a maintained array instead of rebuilding player lists repeatedly.


```lua
local plyCache = {}

local function dataOf(ply)
    if not IsValid(ply) then return nil end
    local k = ply:EntIndex()
    local d = plyCache[k]
    if d then return d end

    d = {
        bullets = 0,
        lastShot = 0,
    }
    plyCache[k] = d
    return d
end

function AddPlayerBullets(ply, n)
    local d = dataOf(ply)
    if d then
        d.bullets = d.bullets + n
    end
end

function GetPlayerBullets(ply)
    local d = dataOf(ply)
    return d and d.bullets or 0
end

hook.Add("PlayerDisconnected", "ClearPlyTempCache", function(ply)
    plyCache[ply:EntIndex()] = nil
end)
```
Reason: Plain Lua arrays by `ply:EntIndex()` are faster for hot reads than `ply.someField` because they bypass player userdata/metatable lookup and keep temp data in a dedicated cache table.


Answer must contain 0 through 1 candidate loops.

```lua
-- Prefer this for fixed collections: dense array (integer keys)
local fixed = {
    10,
    20,
    30,
    40,
    50,
}

-- Slowest-for-comparison shape: string-keyed map
local fixed_map = {
    a = 10,
    b = 20,
    c = 30,
    d = 40,
    e = 50,
}

local function sum_array(t)
    local total = 0
    for i = 1, #t do
        total = total + t[i]
    end
    return total
end

local function sum_map(t)
    local total = 0
    for _, v in pairs(t) do
        total = total + v
    end
    return total
end

local function bench()
    local runs = 200000
    local a, b = 0, 0
    local start

    start = SysTime()
    for i = 1, runs do
        a = a + sum_array(fixed)
    end
    print("array", SysTime() - start)

    start = SysTime()
    for i = 1, runs do
        b = b + sum_map(fixed_map)
    end
    print("map", SysTime() - start)

    print("sink", a + b)
end

bench()
```
Reason: Use a dense numeric-indexed array (`{1,2,3...}`) and iterate with `for i=1,#t` when the set of keys is fixed, because Garry's Mod/Lua tables keep numeric sequences contiguous and `pairs` on string-key maps is hash-based and slower.


```lua
local r, g, b, a = 255, 64, 0, 200

hook.Add("HUDPaint", "FastDraw", function()
    -- hot path: pass numbers directly
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(16, 16, 128, 32)
end)
```
Reason: Passing `r,g,b,a` directly avoids creating/allocating a `Color` table and avoids per-call field lookups, so it is the lower-overhead form for tight draw loops.


```lua
local steamID = "STEAM_0:1:12345678"
local row = sql.QueryRow("SELECT coins FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
if row then
    print(row.coins)
end
```
Reason: Local SQLite (`sql` library) is typically lower latency on a single Garry's Mod server because it is in-process with no network round-trips, so read/write calls are usually faster than remote MySQL for this setup.


```lua
local steamIDCache = setmetatable({}, { __mode = "k" }) -- weak-keys: auto cleanup when players GC

local function cacheSteamID(ply)
    local cached = steamIDCache[ply]
    if cached then return cached end

    local sid = ply:SteamID()
    steamIDCache[ply] = sid
    return sid
end

hook.Add("PlayerInitialSpawn", "CacheSteamID_OnSpawn", function(ply)
    steamIDCache[ply] = ply:SteamID()
end)

hook.Add("PlayerDisconnected", "CacheSteamID_OnDisconnect", function(ply)
    steamIDCache[ply] = nil
end)

-- hot path: use cacheSteamID(ply) instead of ply:SteamID()
local function OnHotPathTick(ply)
    local sid = cacheSteamID(ply)
    -- use sid repeatedly here
    return sid
end
```
Reason: Cache the SteamID once per player and reuse it on hot-path calls, clearing the entry on disconnect (and using weak keys for safety) to avoid repeated expensive `ply:SteamID()` lookups.


```lua
-- Fast path
local function buildMessageFast(count)
    local parts = {}
    parts[#parts + 1] = "start"

    for i = 1, count do
        parts[#parts + 1] = tostring(i)
        parts[#parts + 1] = "-"
        parts[#parts + 1] = "item,"
    end

    parts[#parts + 1] = "end"
    return table.concat(parts) -- one allocation pass
end

-- Slow path (avoid)
-- local s = ""
-- for i = 1, count do
--     s = s .. tostring(i) .. "-item," -- repeated allocations
-- end

local big = buildMessageFast(50000)
print(big)
```
Reason: In Lua, concatenating many small strings with `..` inside a loop repeatedly reallocates/copies the growing string, while collecting chunks in a table and calling `table.concat` once performs linear-time assembly with far fewer allocations.


```lua
-- faster for non-rounded quads than draw.RoundedBox(0,...)
local SetDrawColor = surface.SetDrawColor
local DrawRect = surface.DrawRect

local function DrawManyRects(rects)
    for i = 1, #rects do
        local rc = rects[i]
        SetDrawColor(rc.r or 255, rc.g or 255, rc.b or 255, rc.a or 255)
        DrawRect(rc.x, rc.y, rc.w, rc.h)
    end
end
```
Reason: `draw.RoundedBox(0, ...)` still goes through rounded-box logic, while `surface.DrawRect` is the direct primitive path for solid rectangles and skips corner/shape overhead.


```lua
local FONT = "DermaLarge"
local TEXT_COLOR = Color(255, 255, 255, 255)

surface.CreateFont(FONT, {
    font = "Arial",
    size = 22,
    weight = 600,
    antialias = true,
    additive = false,
})

hook.Add("HUDPaint", "FastSingleLineText", function()
    local txt = "Health: " .. LocalPlayer():Health()

    surface.SetFont(FONT)
    surface.SetTextColor(TEXT_COLOR)
    surface.SetTextPos(16, 16)
    surface.DrawText(txt)
end)
```
Reason: Use the low-level `surface.SetFont`, `SetTextColor`, `SetTextPos`, `DrawText` path to avoid the extra wrapping logic in `draw.DrawText`/`SimpleTextOutlined` (alignment, optional shadows/flags) for per-frame single-line text.


```lua
-- Preferred for sequential array-like tables
local n = #tbl
```
Reason: Garry's Mod Lua follows standard Lua for array-like tables, and `#` returns the sequence length (highest contiguous integer index from 1), which is the correct and fastest operator for ordered array-style tables.


```lua
-- Fastest way to discard and reuse a large sequential table when variable can be rebound.
-- Rebind the local/table variable to a brand new table.
arr = {}
```
Reason: Rebinding with `arr = {}` is O(1), while `table.Empty(arr)` still has to traverse and clear each element, so for repeated high-frequency resets the assignment is generally faster and cheaper unless you must preserve all existing references to `arr`.


```lua
-- Build as a set (map) once, not a list.
local validCommands = {
    ["give"] = true,
    ["take"] = true,
    ["reload"] = true,
    ["jump"] = true,
}

local function hasCommand(cmd)
    return validCommands[cmd] == true
end

-- Faster than table.HasValue("command", list), which scans every element.
if hasCommand("reload") then
    print("command exists")
end
```
Reason: table lookups by key are O(1) in Lua, so a set-table is much faster than table.HasValue’s linear scan through a list.


```lua
local t = {
    pos = Vector(0, 0, 0),
    hp = 100,
    name = "player_1",
    alive = true,
}
```
Reason: In Garry's Mod Lua (Lua 5.1), constructing with a literal is faster because the table is created and populated in one operation, while `{}` plus later assignments does extra assignment work on an extra object state.


```lua
local function randomFromSequential(t)
    local n = #t
    if n == 0 then return nil end
    return t[math.random(1, n)]
end
```
Reason: `table.Random` handles non-sequential keys and mixed tables, so direct indexed lookup via `#t` and `math.random(1, n)` avoids those extra checks and hash overhead for array-like tables.


```lua
for i = 1, n do
    local x = values[i]
    out[i] = x * x
end
```
Reason: Use `x * x`; it is the fastest form in Lua/Garry's Mod because it is a direct arithmetic operation, while `math.pow(x, 2)` or bit tricks add extra overhead in a tight loop.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- process each connected player
    print(ply:Nick())
end
```
Reason: `player.GetAll()` returns all currently connected players, and `ipairs` iterates every player entry.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    if not IsValid(ent) then
        continue
    end

    -- process ent
end
```
Reason: `ents.FindByClass("prop_physics")` asks the engine for only `prop_physics` entities, so the loop never builds an upfront table of all entities in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- your Think logic here
end)
```
Reason: `hook.Add` registers a Think hook callback under the unique identifier `MyAddon.Think` so the function is called each tick.


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: `IsValid(ent)` is the Garry's Mod Lua validity check that safely handles `nil` and removed entities, so calls inside the block won't run on dead/deleted entities.


```lua
if SERVER then
    util.AddNetworkString("MyAddon.Sync")
end

net.Receive("MyAddon.Sync", function(len, ply)
    -- handler runs when MyAddon.Sync arrives
    local payload = net.ReadString()
    print("Received:", payload)
end)
```
Reason: `net.Receive` is GMod's inbound network callback registration for a message name, and `util.AddNetworkString` exposes that message from client->server when used on server.


```lua
-- Pre-allocate once, reset in-place in the hot loop.
-- No Angle() call per iteration.
local anglePool = { Angle(), Angle(), Angle() }
local poolI = 0

local function GetZeroAngle()
    poolI = (poolI % #anglePool) + 1
    local a = anglePool[poolI]
    a.p, a.y, a.r = 0, 0, 0
    return a
end

for i = 1, 1000000 do
    local ang = GetZeroAngle()
    -- use ang
end
```
Reason: Reusing/resetting preallocated Angle objects avoids per-iteration userdata allocation and GC pressure from `Angle()` in the hot path; use a small pool only if re-entrant calls can overlap.


```lua
local addonColor = myaddon.config.color

local function shouldUseColor()
    local c = addonColor
    return c
end
```
Reason: Cache the setting in a local, because local lookup is cheaper than global/table chain lookups (`myaddon` + `config` + `color`) on every hot-path read.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred DarkRP API (instead of ply:GetNWString("job"))
```
Reason: Use `getDarkRPVar("job")` because it is DarkRP’s versioned, replicated player job accessor, while raw `GetNWString("job")` is low-level NW access and can drift from DarkRP’s intended `DarkRPVar` updates.


```lua
local p1 = Vector(0, 0, 0)
local p2 = Vector(10, 0, 0)
local maxDistance = 15

if p1:DistToSqr(p2) <= maxDistance * maxDistance then
    -- p1 is within 15 units of p2
end
```
Reason: Use `DistToSqr` and compare to `maxDistance^2` to avoid the expensive square-root from `Distance` when only a threshold check is needed.


```lua
if ents.Iterator then
    for ent in ents.Iterator() do
        if IsValid(ent) then
            -- visit entity
        end
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- visit entity
    end
end
```
Reason: Use `ents.Iterator()` first because it is the wiki-recommended efficient entity iterator that avoids allocating the full entities table; fall back to `ents.GetAll()` only when that iterator is unavailable.


```lua
local function FindNearbyEntitiesCheap(ply, radius)
    if not IsValid(ply) then return {} end

    local pos = ply:GetPos()
    local range = Vector(radius, radius, radius)
    local candidates = ents.FindInBox(pos - range, pos + range)

    local out, n = {}, 0
    local r2 = radius * radius

    for i = 1, #candidates do
        local ent = candidates[i]
        if ent ~= ply and IsValid(ent) and ent:GetPos():DistToSqr(pos) <= r2 then
            n = n + 1
            out[n] = ent
        end
    end

    return out
end
```
Reason: Use `ents.FindInBox` as a cheap broad-phase spatial query and post-filter by `DistToSqr` for true sphere distance, which is a common faster FindIn* alternative to `FindInPVS` in server-side proximity checks.


```lua
local function getPlayersInRadius(center, radius)
    local rsq = radius * radius
    local out = {}

    for _, ply in ipairs(player.GetAll()) do
        if ply:Alive() and ply:GetPos():DistToSqr(center) <= rsq then
            out[#out + 1] = ply
        end
    end

    return out
end

-- Example
local players = getPlayersInRadius(Vector(0, 0, 0), 512)
```
Reason: Iterate connected players directly and use `DistToSqr` so the query stays O(players) and avoids allocating/scanning every nearby entity that `ents.FindInSphere` would return.


```lua
local n = 1000000
local total = 0

for i = 1, n do
    total = total + 1
end
```
Reason: `for i = 1, n do` is usually faster in Garry's Mod Lua because the numeric `for` uses optimized loop bytecode, while a `while` loop does extra manual increment/compare work each iteration.


```lua
-- Faster: one hook dispatch per tick, pass all players
local TICK_HOOK = "MyTickAllPlayers"

hook.Add("Think", "DispatchPlayerTick", function()
    local players = player.GetAll()   -- one table capture
    hook.Run(TICK_HOOK, players, CurTime(), FrameTime())
end)

hook.Add(TICK_HOOK, "HandlePlayerTick", function(players, now, ft)
    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) then
            -- custom per-player logic here
        end
    end
end)

-- Slower pattern to avoid:
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("HandleSinglePlayerTick", ply, CurTime(), FrameTime())
-- end
```
Reason: Dispatching one `hook.Run` per tick is faster because hook dispatch, lookup, and call setup happen once instead of once per player, with only one controlled loop for your own logic.


```lua
hook.Add("HUDPaint", "FastHealthHUD", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end

    local hp = ply:Health()
    local hpText = hp .. " HP"

    surface.SetDrawColor(0, 0, 0, 180)
    surface.DrawRect(16, 16, 160, 60)
    draw.SimpleText(hpText, "DermaLarge", 20, 24, Color(255, 255, 255, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText("Health", "DermaDefault", 20, 54, Color(180, 180, 180, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText("x" .. hp, "DermaDefault", 172, 32, Color(255, 200, 0, 255), TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP)
end)
```
Reason: Cache `LocalPlayer()` and `:Health()` once per `HUDPaint` call so all three draw calls use the same local value, avoiding repeated native lookups.


```lua
-- module/file scope
local WHITE = color_white   -- one Color object, not recreated in paint

function PANEL:Paint(w, h)
    if not self.entries or #self.entries == 0 then return end

    surface.SetDrawColor(WHITE)

    for i = 1, #self.entries do
        local e = self.entries[i]
        surface.DrawRect(e.x, e.y, e.w, e.h)
    end
end
```
Reason: `Color()` allocates a new color each call, so build once and reuse it (or use `color_white`) by setting draw color before the loop, since the color is invariant across iterations.


```lua
local sin = math.sin

for i = 1, 100000 do
    local angle = i * 0.01
    result[i] = sin(angle)
end
```
Reason: Caching `math.sin` in a local removes a table/global lookup each iteration, so the hot loop uses a fast local variable lookup instead of repeated `math` field access.


```lua
-- Client-side: cache LocalPlayer once, refresh only when needed
local lp = nil

local function refreshLocalPlayer()
    local p = LocalPlayer()
    if IsValid(p) then
        lp = p
    end
end

hook.Add("InitPostEntity", "cache_localplayer", refreshLocalPlayer)

hook.Add("Think", "ensure_localplayer_cached", function()
    if not IsValid(lp) then
        refreshLocalPlayer()
    end
end)

local function DoHotWork()
    local ply = lp -- no LocalPlayer() lookup here
    if not IsValid(ply) then return end

    -- use ply repeatedly
end
```
Reason: Cache `LocalPlayer()` in a local upvalue and only refresh it on cache miss/startup so hot code reads a pre-fetched local player reference instead of repeatedly calling the global lookup.


```lua
local LOOK_COS = math.cos(math.rad(35))
local LOOK_COS2 = LOOK_COS * LOOK_COS
local MAX_DIST_SQR = 1000 * 1000

local function AreLookingAtEachOther(plyA, plyB)
    if not IsValid(plyA) or not IsValid(plyB) then return false end

    local posA = plyA:EyePos()
    local posB = plyB:EyePos()
    local toB = posB - posA
    local distSqr = toB:LengthSqr()

    if distSqr <= 0 or distSqr > MAX_DIST_SQR then return false end

    local aForward = plyA:EyeAngles():Forward()
    local bForward = plyB:EyeAngles():Forward()

    local aDot = aForward:Dot(toB)            -- wants A looking toward B
    if aDot <= 0 or aDot * aDot < LOOK_COS2 * distSqr then return false end

    local bDot = bForward:Dot(-toB)           -- wants B looking toward A
    if bDot <= 0 or bDot * bDot < LOOK_COS2 * distSqr then return false end

    return true
end
```
Reason: This checks both gaze directions with vector dot products against a cosine threshold (and avoids `acos`), using squared values to skip square roots for a very cheap, rough face-to-face test.


```lua
SomeHelper(ply)
```
Reason: `ply:SomeHelper()` is syntax sugar for `ply.SomeHelper(ply)`, so in Luа the call overhead is equivalent; in hot paths, performance differences are negligible and you should choose the form based on design (standalone helper vs true method).


```lua
local console = Msg -- cache global lookup once

-- inside hot loop/hot path
console("[DBG] id=" .. tostring(entID) .. " hp=" .. hp .. "\n")
```
Reason: `Msg` is a lower-overhead GMod console writer than `print`, since it skips `print`'s vararg/tostring+tab+newline formatting and writes one precomposed string directly.


```lua
-- fastest typical loop for a dense numeric array in Garry's Mod Lua
local arr = { 1, 2, 3, 4, 5 }
local n = #arr
for i = 1, n do
    local v = arr[i]
    -- process v
end
```
Reason: For dense, numeric-indexed arrays, a numeric `for` with cached `#arr` is fastest because it does direct array indexing in the VM loop, while `ipairs`/`pairs` add iterator-call overhead and `pairs` is hash-walk based (slower and non-sequential).


```lua
-- DarkRP fn style does Filter(...)->Map(...) creating intermediate tables.
-- Do both steps in one pass instead.

local function transformPlayers(players)
    local out = {}
    local n = 0

    for i = 1, #players do
        local ply = players[i]

        -- filter
        if IsValid(ply) and ply:Alive() and not ply:IsAFK() then
            -- map
            n = n + 1
            out[n] = {
                name = ply:Nick(),
                steamid = ply:SteamID64(),
                money = ply:getDarkRPVar("money")
            }
        end
    end

    return out
end

local filteredMapped = transformPlayers(player.GetAll())
```
Reason: One pass, one output table, and no fn combinator chaining means fewer function calls, no intermediate tables, and lower GC pressure than fn.Filter+fn.Map in Garry's Mod Lua.


```lua
local cachedPlayers = {}
local cachedPlayerIndex = {}

local function AddCachedPlayer(ply)
    if not IsValid(ply) or cachedPlayerIndex[ply] then return end
    cachedPlayerIndex[ply] = #cachedPlayers + 1
    cachedPlayers[#cachedPlayers + 1] = ply
end

local function RemoveCachedPlayer(ply)
    local idx = cachedPlayerIndex[ply]
    if not idx then return end

    local lastIdx = #cachedPlayers
    local lastPly = cachedPlayers[lastIdx]

    cachedPlayers[idx] = lastPly
    cachedPlayerIndex[lastPly] = idx

    cachedPlayers[lastIdx] = nil
    cachedPlayerIndex[ply] = nil
end

hook.Add("PlayerInitialSpawn", "MyPlayerCache_Add", function(ply)
    AddCachedPlayer(ply)
end)

hook.Add("PlayerDisconnected", "MyPlayerCache_Remove", function(ply)
    RemoveCachedPlayer(ply)
end)

hook.Add("Think", "MyThinkCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- do per-tick work on ply here
        end
    end
end)
```
Reason: Use a mutable cache updated only in `PlayerInitialSpawn` and `PlayerDisconnected`, then iterate that cached list in `Think` so `player.GetAll()` is not called every tick.


```lua
local plyCache = {} -- [ply:EntIndex()] = player temp state table

local function cacheFor(ply)
    local idx = ply:EntIndex()
    local c = plyCache[idx]
    if not c then
        c = {}
        plyCache[idx] = c
    end
    return c
end

-- write
function setTempValue(ply, v)
    cacheFor(ply).someField = v
end

-- fast read in hot loops
function getTempValue(ply)
    local c = plyCache[ply:EntIndex()]
    return c and c.someField or nil
end

hook.Add("PlayerDisconnected", "ClearPlyCache", function(ply)
    plyCache[ply:EntIndex()] = nil
end)
```
Reason: Store per-player temp data in an EntIndex-keyed Lua table so hot reads are plain integer-key table lookups, avoiding entity-table/metatable overhead from assigning properties directly on `ply`.


```lua
local values = { "a", "b", "c", "d", "e" } -- contiguous numeric keys (array shape)
local byName = { a = "a", b = "b", c = "c", d = "d", e = "e" } -- string-keyed map shape

local sum_array = 0
for i = 1, #values do
    local v = values[i]
    sum_array = sum_array + i
end

local sum_map = 0
for _k, v in pairs(byName) do
    sum_map = sum_map + string.len(v)
end
```
Reason: Use a contiguous number-keyed array (`1..n` with `ipairs`/numeric `for`) for fixed collections because it iterates via Lua's dense array path, which is faster and more cache-friendly than hashing string keys in a map.


```lua
-- Fast path for hot draw: keep function references and raw color scalars
local SetDrawColor = surface.SetDrawColor
local DrawRect = surface.DrawRect

local r, g, b, a = 30, 180, 255, 255

hook.Add("PostRenderVGUI", "FastDrawPath", function()
    for i = 1, 256 do
        SetDrawColor(r, g, b, a)
        DrawRect(10, 10 + i, 128, 2)
    end
end)
```
Reason: Using `SetDrawColor(r, g, b, a)` in a cached-upvalue path avoids constructing or indexing a `Color` object on each draw call, which is the cheaper form for hot loops.


```lua
local steamID = "STEAM_0:1:123456"

-- SQLite (local, sql library)
local row = sql.QueryRow("SELECT coins FROM player_data WHERE steamid = " .. SQLStr(steamID))

if row then
    print("coins:", tonumber(row.coins))
else
    sql.Query("INSERT INTO player_data (steamid, coins) VALUES (" .. SQLStr(steamID) .. ", 0)")
end
```
Reason: On a single GMod server with no cross-server sync, local SQLite via the built-in `sql` API is typically lower latency because it avoids remote network/database server round-trips, reducing read/write overhead compared with MySQL.


```lua
local steamIDCache = setmetatable({}, { __mode = "k" }) -- weak keys, auto-free disconnected players

local function GetCachedSteamID(ply)
    if not IsValid(ply) then return nil end

    local sid = steamIDCache[ply]
    if sid == nil then
        sid = ply:SteamID()
        steamIDCache[ply] = sid
    end

    return sid
end

hook.Add("PlayerDisconnected", "cache_purge_steamid", function(ply)
    steamIDCache[ply] = nil
end)

-- hot path
hook.Add("Think", "example_hotpath", function()
    for _, ply in ipairs(player.GetAll()) do
        local sid = GetCachedSteamID(ply)
        -- use sid
    end
end)
```
Reason: Cache each player's SteamID once per entity in a weak-key Lua table so hot-path code uses O(1) local lookups instead of repeated `ply:SteamID()` calls, and clear on disconnect to prevent stale entries.


```lua
-- Slow: repeated concatenation in a loop (creates new strings each step)
local slow = ""
for i = 1, 5000 do
    slow = slow .. "piece " .. i .. ", "
end

-- Fast: collect chunks then concatenate once
local chunks = {}
for i = 1, 5000 do
    chunks[#chunks + 1] = "piece " .. i .. ", "
end
local fast = table.concat(chunks)
```
Reason: `table.concat` concatenates all pieces in one C-level pass, avoiding the repeated reallocations and copies caused by `..` in a loop.


```lua
-- faster for non-rounded filled rectangles in GMod
local setDrawColor = surface.SetDrawColor
local drawRect = surface.DrawRect

for _, r in ipairs(rects) do
    setDrawColor(r.r, r.g, r.b, r.a or 255)
    drawRect(r.x, r.y, r.w, r.h)
end
```
Reason: Use `surface.SetDrawColor` + `surface.DrawRect` to skip the rounded-box path (`draw.RoundedBox` uses extra corner/border logic) and avoid function-level corner handling when drawing plain filled rectangles.


```lua
-- Pre-create once
surface.CreateFont("FastHUDFont", {
    font = "Roboto",
    size = 24,
    weight = 500,
    antialias = true
})

local msg = "Ready"
local x, y = 16, 16

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("FastHUDFont")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(x, y)
    surface.DrawText(msg)
end)
```
Reason: Use only the low-level `surface.*` text path (`SetFont`, `SetTextColor`, `SetTextPos`, `DrawText`) because it avoids the extra alignment, parsing, and outline/shadow work done by `draw.DrawText` and `SimpleTextOutlined` while drawing one line each frame.


```lua
local arr = {10, 20, 30}
local n = #arr
```
Reason: `#arr` is the canonical Lua length operator for sequential (1-based, contiguous) array-like tables, which is what Garry's Mod Lua expects for normal list-style tables.


```lua
-- Fast path for frequent full clears of a large array-like table
t = {}
```
Reason: `t = {}` is generally faster because it drops the old table in O(1), while `table.Empty(t)` must clear each key/value pair (O(n)); only use `table.Empty` when you must preserve existing table identity for other references.


```lua
local roleList = {
    "admin",
    "moderator",
    "superadmin",
}

local function MakeSet(values)
    local set = {}
    for _, v in ipairs(values) do
        set[v] = true
    end
    return set
end

local roleSet = MakeSet(roleList)

local role = "moderator"
if roleSet[role] then
    print("allowed")
else
    print("denied")
end

-- slower equivalent on a list:
-- if table.HasValue(roleList, role) then ...
-- that call loops every element each time
```
Reason: Use a set-map table (`set[value] = true`) for O(1) lookups instead of `table.HasValue`, which does an O(n) scan on the list each check.


```lua
-- Faster: initialize known fields directly in the constructor.
local t = { health = 100, armor = 50, speed = 250 }
```
Reason: `local t = { ... }` does one allocation plus immediate field setup, while `local t = {}; t.health = ...` adds extra assignment steps and table writes.


```lua
local function randomFromSequential(tbl)
    local n = #tbl
    if n == 0 then return nil end
    return tbl[math.random(1, n)]
end
```

Reason: For a sequential array, indexing directly with a precomputed `math.random(1, #tbl)` is O(1), avoiding `table.Random`'s extra key scanning/dispatch and mixed-key handling overhead.


```lua
local acc = 0

for i = 1, 1000000 do
    local x2 = x * x
    acc = acc + x2
end
```
Reason: `x * x` is the preferred fast form in Lua/GLua hot paths, avoiding `math.pow`/`^2` overhead and keeping a single integer/float multiply.


```lua
for _, ply in ipairs(player.GetAll()) do
    print(ply:Nick())
end
```
Reason: `player.GetAll()` returns all connected players, and `ipairs` safely iterates the list entries exactly once in numeric order.


```lua
for ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- do something with this prop_physics entity
    end
end
```
Reason: `ents.Iterator()` walks the entity list directly, so you avoid creating a full table first like `ents.GetAll()` or `ents.FindByClass()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```
Reason: `hook.Add` registers your function on the `Think` event and the string `MyAddon.Think` is the hook identifier used to track/remove that specific callback.


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: `IsValid(ent)` is the standard GMod guard that returns false for nil/invalid/deleted entities, so methods are only called on a safe entity reference.


```lua
if SERVER then
    util.AddNetworkString("MyAddon.Sync")

    net.Receive("MyAddon.Sync", function(len, ply)
        local payload = net.ReadString()
        -- handle incoming message from client
    end)
else
    net.Receive("MyAddon.Sync", function(len)
        local payload = net.ReadString()
        -- handle incoming message from server
    end)
end
```
Reason: `net.Receive` binds a handler to incoming net traffic for `MyAddon.Sync`, and the server must call `util.AddNetworkString("MyAddon.Sync")` so the message is allowed on the wire.


```lua
-- Hot-path zero angle cache (no Angle() allocation per call)
local zeroPool = {
    Angle(),
    Angle(),
    Angle(),
    Angle(),
}

local poolI = 0

local function TakeZeroAngle()
    poolI = poolI + 1
    if poolI > #zeroPool then poolI = 1 end

    local a = zeroPool[poolI]
    a.p, a.y, a.r = 0, 0, 0 -- reset in-place
    return a
end

-- use:
-- local ang = TakeZeroAngle()
-- ent:SetAngles(ang)
```
Reason: Reset one reusable Angle from a small pool each call instead of calling Angle() each time, avoiding repeated userdata allocations and GC churn in the hot path.


```lua
-- Cache the setting once to a flat local for hot-path reads
local addonColor = myaddon.config.color

-- Frequently read access
local function DrawHUD()
    local col = addonColor
    -- use col
end
```
Reason: A local variable is the fastest to read in Lua (direct slot access) while `myaddon.config.color` requires repeated global/table lookups, so cache it flat locally in hot paths; only refresh the local if the setting changes at runtime.


```lua
-- Preferred DarkRP API (instead of legacy NW)
local jobName = ply:getDarkRPVar("job")

-- Optional alternative if you need the full job table
local jobNameFromTeam = ply:getJobTable().name
```
Reason: `getDarkRPVar("job")` is the DarkRP accessor for the replicated job value, so it stays aligned with DarkRP state changes better than using the generic `GetNWString("job")`.


```lua
local posA = Vector(0, 0, 0)
local posB = Vector(64, 0, 0)
local range = 128 -- units

if posA:DistToSqr(posB) <= range * range then
    print("within range")
end
```
Reason: `Vector:DistToSqr` compares squared distance directly, so you avoid the expensive square-root in `Distance`/`Length` when only threshold checking is needed.


```lua
if ents.Iterator then
    for ent in ents.Iterator() do
        if IsValid(ent) then
            -- Handle each entity.
        end
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        if IsValid(ent) then
            -- Handle each entity.
        end
    end
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient entity enumerator because it avoids allocating a full entity table on each pass; fallback to `ents.GetAll()` only if the iterator is unavailable.


```lua
-- Server-side: near-player entity query using a faster broad-phase primitive.
-- Replace find in a sphere with box-first filtering, then exact radius check.
function GetNearbyEntitiesNearPlayer(ply, radius)
    local origin = ply:GetPos()
    local extent = Vector(radius, radius, radius)
    local mins = origin - extent
    local maxs = origin + extent

    local candidates = ents.FindInBox(mins, maxs)
    local radius2 = radius * radius
    local out = {}
    local n = 0

    for _, ent in ipairs(candidates) do
        if IsValid(ent) and ent ~= ply and ent:GetPos():DistToSqr(origin) <= radius2 then
            n = n + 1
            out[n] = ent
        end
    end

    return out
end
```
Reason: `ents.FindInBox` is commonly faster than `FindInSphere`/`FindInPVS` for broad-phase proximity checks, then `DistToSqr` keeps exact radius filtering cheap.


```lua
local function GetPlayersInRadius(origin, radius)
    local radiusSq = radius * radius
    local out = {}
    local players = player.GetAll()

    for i = 1, #players do
        local ply = players[i]
        if ply:GetPos():DistToSqr(origin) <= radiusSq then
            out[#out + 1] = ply
        end
    end

    return out
end
```
Reason: `player.GetAll()` limits traversal to player entities only and `DistToSqr` avoids `sqrt`, so you skip scanning and filtering thousands of non-player ents from `ents.FindInSphere`.


```lua
local n = 1000000
for i = 1, n do
    -- hot loop work
end
```
Reason: Use the numeric `for` loop for fixed 1..n counting because it has the lowest per-iteration overhead in Lua/LuaJIT, while a `while` version does extra manual increment/check work.


```lua
-- Faster pattern: one hook dispatch per tick
local TICK_HOOK = "PerfDemo.Tick"
local PLAYER_BATCH_HOOK = "PerfDemo.ProcessPlayerBatch"

hook.Add("Think", TICK_HOOK, function()
    local players = player.GetAll()
    hook.Run(PLAYER_BATCH_HOOK, players)
end)

hook.Add(PLAYER_BATCH_HOOK, "PerfDemo.ProcessPlayerBatchImpl", function(players)
    local count = #players
    for i = 1, count do
        local ply = players[i]
        if IsValid(ply) then
            -- custom per-player logic goes here
        end
    end
end)

-- Slower pattern to avoid:
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("PerfDemo.ProcessPlayer", ply)
-- end
```
Reason: One `hook.Run` call avoids repeated hook-dispatch overhead; doing the per-player loop once inside the callback keeps the same work but with fewer dispatches every tick.


```lua
hook.Add("HUDPaint", "FastHealthHUD", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end

    local health = ply:Health()
    local label = "HP: " .. health

    draw.RoundedBox(6, 20, 20, 220, 24, Color(0, 0, 0, 180))
    draw.RoundedBox(6, 22, 22, math.max(0, health * 2), 20, Color(0, 180, 0, 220))
    draw.SimpleText(label, "DermaLarge", 130, 32, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end)
```
Reason: Cache `LocalPlayer()` and `Health()` once in local variables so all three draw calls reuse the same value instead of recomputing the lookup each time.


```lua
-- Cache the color once, not per-iteration
local WHITE = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "FastPaintLoop", function()
    local items = getItemsToDraw()
    if #items == 0 then return end

    surface.SetDrawColor(WHITE)

    for i = 1, #items do
        local it = items[i]
        surface.DrawRect(it.x, it.y, it.w, it.h)
    end
end)
```
Reason: `Color(255,255,255)` creates a new color object every loop iteration, while reusing one cached color and setting it once before the loop removes repeated allocations and lowers per-frame overhead in a paint path.


```lua
local sin = math.sin -- cache once to avoid repeated math table lookup in hot path

local function tick(count, x)
    local sum = 0
    for i = 1, count do
        sum = sum + sin(x + i)
    end
    return sum
end

-- Called frequently:
local result = tick(100000, 1.25)
```
Reason: This turns repeated global `math` table lookups (`math.sin`) into one local upvalue access (`sin`), which is faster in Lua hot loops.


```lua
local cachedLocalPlayer

local function GetLocalPlayer()
    local ply = cachedLocalPlayer
    if not IsValid(ply) then
        ply = LocalPlayer()
        cachedLocalPlayer = ply
    end
    return ply
end

hook.Add("Think", "example_fast_localplayer", function()
    local ply = GetLocalPlayer()
    if not IsValid(ply) then return end

    -- use ply repeatedly in this frame
    if ply:KeyDown(IN_ATTACK) then
        -- ...
    end
end)
```
Reason: Cache `LocalPlayer()` in a local upvalue and only refresh when invalid to avoid repeated lookups in hot code paths.


```lua
local LOOK_DOT = math.cos(math.rad(35))      -- ~35° cone (~70° total FOV)
local MAX_DIST_SQ = 1000 * 1000             -- optional far-distance cut

local function RoughlyLookingAtEachOther(p1, p2)
    if not IsValid(p1) or not IsValid(p2) then return false end

    local dir = p2:EyePos() - p1:EyePos()
    if dir:LengthSqr() > MAX_DIST_SQ then return false end
    if dir:Normalize() == 0 then return false end

    local a1 = p1:GetAimVector()
    local a2 = p2:GetAimVector()

    return a1:Dot(dir) >= LOOK_DOT and a2:Dot(-dir) >= LOOK_DOT
end
```
Reason: Dot-product checks with normalized eye-to-eye vectors stay in O(1) math and avoid costly acos while giving a tunable “roughly facing” test via threshold constants.


```lua
local function SomeHelper(ply)
    -- helper body
end

SomeHelper(ply)
```
Reason: `ply:SomeHelper()` is syntactic sugar for a method-style call, so explicit `SomeHelper(ply)` is usually the better choice for a helper you own because it avoids per-call table method lookup and makes the `self`/argument flow explicit.


```lua
local log = MsgN

if debugEnabled then
    log("[DBG] " .. tostring(entIndex) .. " x=" .. tostring(pos.x) .. " y=" .. tostring(pos.y))
end
```
Reason: `MsgN`/`Msg` writes one prebuilt string directly to the console, avoiding `print`'s slower vararg formatting and spacing logic in a hot loop.


```lua
local nums = {1, 2, 3, 4, 5, 6}
local sum = 0

local n = #nums
for i = 1, n do
    sum = sum + nums[i]
end
```
Reason: Use numeric `for` on a dense, 1-based array (`for i = 1, #t`) because Garry's Mod Lua/JIT handles it with direct array indexing and one-time bounds evaluation, while `ipairs`/`pairs` pay extra iterator and dispatch overhead.


```lua
-- Faster DarkRP list transform than fn.Filter + fn.Map: one pass, no intermediate tables.
local function getAliveCitizenNicks()
    local players = player.GetAll()
    local out = {}
    local outCount = 0

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply)
            and not ply:IsBot()
            and ply:Alive()
            and ply:Team() == TEAM_CITIZEN
        then
            outCount = outCount + 1
            out[outCount] = ply:Nick()
        end
    end

    return out
end

local names = getAliveCitizenNicks()
```
Reason: A single direct loop fuses filter+map into one step, avoids fn's combinator chain allocations/calls, and only allocates the final output table.


```lua
local playerCache = {}
local playerIndex = {}

local function cacheAddPlayer(ply)
    if not IsValid(ply) or playerIndex[ply] then return end
    local idx = #playerCache + 1
    playerCache[idx] = ply
    playerIndex[ply] = idx
end

local function cacheRemovePlayer(ply)
    local idx = playerIndex[ply]
    if not idx then return end

    local lastIdx = #playerCache
    local lastPly = playerCache[lastIdx]

    playerCache[idx] = lastPly
    playerIndex[lastPly] = idx

    playerCache[lastIdx] = nil
    playerIndex[ply] = nil
end

-- Seed cache for players already connected at startup/map start
for _, ply in ipairs(player.GetAll()) do
    cacheAddPlayer(ply)
end

hook.Add("PlayerInitialSpawn", "PlayerCache_Add", function(ply)
    cacheAddPlayer(ply)
end)

hook.Add("PlayerDisconnected", "PlayerCache_Remove", function(ply)
    cacheRemovePlayer(ply)
end)

hook.Add("Think", "Think_UseCachedPlayers", function()
    for i = 1, #playerCache do
        local ply = playerCache[i]
        if IsValid(ply) then
            -- do per-tick work with ply
        end
    end
end)
```
Reason: Cache once, then mutate the cache only on PlayerInitialSpawn/PlayerDisconnected so Think never calls player.GetAll() each tick.


```lua
-- Faster temp per-player reads: one plain Lua table keyed by EntIndex
local playerData = {} -- [entIndex] = {shots=0, nextFire=0}

hook.Add("PlayerInitialSpawn", "pdata_init", function(ply)
    playerData[ply:EntIndex()] = { shots = 0, nextFire = 0 }
end)

hook.Add("PlayerDisconnected", "pdata_cleanup", function(ply)
    playerData[ply:EntIndex()] = nil
end)

local function getData(ply)
    return playerData[ply:EntIndex()]
end

hook.Add("Think", "pdata_tick", function()
    for _, ply in ipairs(player.GetAll()) do
        local d = getData(ply)
        if not d then continue end

        if d.nextFire <= CurTime() then
            d.shots = d.shots + 1
            d.nextFire = CurTime() + 0.1
            local shots = d.shots -- fast repeated reads from cached row
        end
    end
end)
```
Reason: Using a local EntIndex-keyed table and a cached row reference removes repeated `ply.someField` entity/meta lookups in hot loops, which is faster for very frequent reads.


```lua
local SIZE = 20000
local REPS = 2000

local map = {}
local arr = {}
for i = 1, SIZE do
    map["k" .. i] = i
    arr[i] = i
end

local function bench_map(t)
    local sum = 0
    local t0 = SysTime()

    for _ = 1, REPS do
        for _, v in pairs(t) do
            sum = sum + v
        end
    end

    return SysTime() - t0, sum
end

local function bench_array(t)
    local sum = 0
    local t0 = SysTime()

    for _ = 1, REPS do
        for i = 1, #t do
            sum = sum + t[i]
        end
    end

    return SysTime() - t0, sum
end

local mapTime, mapSum = bench_map(map)
local arrTime, arrSum = bench_array(arr)

print("map sum:", mapSum, "time:", string.format("%.6f", mapTime))
print("array sum:", arrSum, "time:", string.format("%.6f", arrTime))
print("faster:", (arrTime < mapTime) and "array" or "map")
```
Reason: A sequential number-indexed array is faster because numeric iteration (`for i = 1, #t`) hits the array part directly with contiguous storage and simple indexing, while string-keyed maps iterate hash entries with extra key hashing and lookup overhead.


```lua
local SetDrawColor = surface.SetDrawColor

local r, g, b, a = 220, 80, 20, 255

for i = 1, 1000 do
    SetDrawColor(r, g, b, a) -- faster for hot path: raw numbers
    surface.DrawRect(8, 8, 64, 24)
end
```
Reason: Use the numeric form `surface.SetDrawColor(r, g, b, a)` in hot loops to avoid allocating/decoding a Color object each frame and reduce per-call dispatch overhead.


```lua
local steamID = "STEAM_0:1:12345"
local row = sql.QueryRow("SELECT cash FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
if row then
    print(row.cash)
end
```
Reason: SQLite via `sql.QueryRow` is typically lower latency on a single Garry's Mod server because it avoids network hops and connection pool overhead, so local in-process reads/writes are usually faster than remote MySQL.


```lua
local steamIdCache = setmetatable({}, { __mode = "k" }) -- weak keys, no manual full cleanup needed

local Player = FindMetaTable("Player")

function Player:GetSteamIDCached()
    local sid = steamIdCache[self]
    if sid ~= nil then
        return sid
    end

    sid = self:SteamID()
    steamIdCache[self] = sid
    return sid
end

hook.Add("PlayerAuthed", "cache_steamid", function(ply, steamid)
    steamIdCache[ply] = steamid
end)

hook.Add("PlayerDisconnected", "purge_steamid_cache", function(ply)
    steamIdCache[ply] = nil
end)

-- Hot path
local function MyHotPath(ply)
    local sid = ply:GetSteamIDCached()
    -- use sid repeatedly without extra SteamID() calls
end
```
Reason: Cache SteamID once per player in a weak-key table and invalidate on auth/disconnect so repeated hot-path lookups use cheap table reads instead of repeated native SteamID() calls.


```lua
-- Build thousands of small pieces, as in Garry's Mod Lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece-" .. i
end

-- Slower: repeated concatenation (O(n^2) with many reallocations)
local slow = ""
for i = 1, #pieces do
    slow = slow .. pieces[i]
end

-- Faster: collect in a table and concatenate once
local buf = {}
for i = 1, #pieces do
    buf[i] = pieces[i]
end
local fast = table.concat(buf, "")

print(#slow == #fast, #fast)
```
Reason: In Lua/GLua, `table.concat` builds the final string in one pass with one allocation pattern, while repeated `..` repeatedly reallocates growing strings.


```lua
local SetDrawColor = surface.SetDrawColor
local DrawRect = surface.DrawRect

for _, r in ipairs(rects) do
    SetDrawColor(r.col)
    DrawRect(r.x, r.y, r.w, r.h)
end
```
Reason: For solid non-rounded rectangles, `surface.DrawRect` is the direct primitive and avoids `draw.RoundedBox(0, ...)`'s rounded-box code path, so it is the faster call.


```lua
local x, y = 20, 20
local font = "Trebuchet24"
local white = Color(255, 255, 255, 220)
local status = "Ready"

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(white)
    surface.SetTextPos(x, y)
    surface.DrawText(status)
end)
```
Reason: surface.SetTextPos + surface.DrawText is the lightest path for single-line text in the same frame since draw.DrawText and SimpleTextOutlined add extra alignment/outline/argument processing overhead before they call the underlying surface text draw.


```lua
local arr = {"a", "b", "c"}
local n = #arr
```
Reason: Use the `#` operator; for sequential array-like tables in Garry's Mod Lua it is the idiomatic way to get their element count.


```lua
-- Fast path for frequent full clears of a large sequential table
local function resetTable()
    t = {}          -- generally faster: replaces the table in O(1)
    -- table.Empty(t) -- slower: walks every element and sets it to nil
end
```
Reason: `t = {}` is generally faster for repeated clears because it discards the old table reference immediately (`O(1)`), while `table.Empty(t)` is an in-place `O(n)` loop that touches every element.


```lua
-- Fast membership checks in GMod Lua: use a set (table keyed by value) instead of table.HasValue.
local roleList = {"admin", "mod", "vip"}

-- Build once (could be done at init/load time)
local roleSet = {}
for _, role in ipairs(roleList) do
    roleSet[role] = true
end

-- Fast path
local function hasRole(set, role)
    return set[role] == true
end

-- Slow path (for comparison):
-- local ok = table.HasValue(roleList, role) -- scans whole list O(n)

local plyRole = "mod"
if hasRole(roleSet, plyRole) then
    print("role is allowed")
end
```
Reason: A keyed set gives O(1) hash lookups, while table.HasValue on a list is a linear O(n) scan on every check.


```lua
local t = { health = 100, name = "npc", active = true }
```
Reason: For small, fixed-shape tables in Garry's Mod Lua, the constructor form is faster because it builds the table with known fields in one creation path, avoiding separate post-creation assignment operations.


```lua
local function RandomFromArray(arr)
    local n = #arr
    return n > 0 and arr[math.random(n)] or nil
end

local names = {"Gman", "Alyx", "Barney", "Gordon"}
local pick = RandomFromArray(names)
```
Reason: For a sequential (array-like) table, `table.Random` does extra generic table/key handling, while `arr[math.random(#arr)]` does one bounds lookup with direct numeric indexing and avoids that overhead.


```lua
for i = 1, iterations do
    local sq = x * x
    -- use sq
end
```
Reason: `x * x` is the fastest way to square in Lua; it uses a single multiply opcode versus exponentiation `^`, which is slower and has extra overhead.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- visit each connected player
    -- process ply here
end
```
Reason: `player.GetAll()` in Garry's Mod returns the list of currently connected players, and `ipairs` cleanly iterates that array.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    if IsValid(ent) then
        -- visit ent here
    end
end
```
Reason: `ents.FindByClass("prop_physics")` filters on class before returning results, so you only iterate matching entities instead of first collecting all entities in the map with a full-table pass.


```lua
MyAddon = MyAddon or {}

function MyAddon.Think()
    -- minimal callback body
end

hook.Add("Think", "MyAddon.Think", MyAddon.Think)
```
Reason: Register `MyAddon.Think` with `hook.Add` so the `Think` event calls that callback every frame.


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: Use `IsValid(ent)` as the canonical Garry's Mod guard; it safely rejects `nil`, `NULL`, and removed entities before any method call.


```lua
-- Server: register message and handler
if SERVER then
    util.AddNetworkString("MyAddon.Sync")

    net.Receive("MyAddon.Sync", function(len, ply)
        local payload = net.ReadString() -- or net.ReadTable()/ReadUInt/etc depending on payload type
        print("Got MyAddon.Sync from", ply:Nick(), payload)
    end)
end
```
Reason: `net.Receive` binds a callback to the incoming `MyAddon.Sync` network message, and `util.AddNetworkString` on the server makes that message name valid for client->server sending.


```lua
local ZERO_ANGLE_POOL = {}
for i = 1, 16 do
    ZERO_ANGLE_POOL[i] = Angle(0, 0, 0)
end

local zero_idx = 0
local function freshZeroAngle()
    zero_idx = zero_idx + 1
    if zero_idx > #ZERO_ANGLE_POOL then
        zero_idx = 1
    end

    local a = ZERO_ANGLE_POOL[zero_idx]
    a.p, a.y, a.r = 0, 0, 0
    return a
end

-- hot path:
-- local ang = freshZeroAngle()  -- reuse+clear, no Angle() allocation
```
Reason: Reusing a small Angle pool and clearing fields in-place avoids per-call Angle() allocations and GC churn in hot code paths.


```lua
local ADDON_COLOR = myaddon.config.color

local color = ADDON_COLOR
```
Reason: A flat local (`ADDON_COLOR`) is fastest for hot reads because local variable access is direct, while globals go through `_G` and `myaddon.config.color` adds extra table lookups per read.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: `ply:GetDarkRPVar("job")` is the DarkRP API for this data, so it stays in sync with DarkRP internals, unlike legacy `GetNWString("job")` which is a lower-level NW var access that can bypass DarkRP conventions.


```lua
local a = Vector(0, 0, 0)
local b = Vector(64, 0, 0)
local maxDist = 128

if a:DistToSqr(b) < maxDist * maxDist then
    -- close enough
end
```
Reason: Use Vector:DistToSqr(other), which compares squared distance directly and avoids the expensive sqrt needed by DistTo (or Length) for threshold-only checks.


```lua
if ents.Iterator then
    for ent in ents.Iterator() do
        if IsValid(ent) then
            -- visit ent
        end
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        if IsValid(ent) then
            -- visit ent
        end
    end
end
```
Reason: `ents.Iterator()` is the wiki-recommended no-allocation way to enumerate every entity, so it’s used first, with `ents.GetAll()` as a compatibility fallback when that iterator isn't available.


```lua
local function GetNearbyEntities(ply, radius)
    local origin = ply:GetPos()
    local half = Vector(radius, radius, radius)
    local radiusSqr = radius * radius

    local nearby = {}
    for _, ent in ipairs(ents.FindInBox(origin - half, origin + half)) do
        if ent ~= ply and ent:GetPos():DistToSqr(origin) <= radiusSqr then
            nearby[#nearby + 1] = ent
        end
    end

    return nearby
end
```
Reason: `ents.FindInBox` is a faster built-in broad-phase spatial query in common GMod benchmarks for nearby checks, and the final squared-distance filter keeps it exact without using `FindInPVS`.


```lua
local function playersWithinRadius(center, radius)
    local radiusSq = radius * radius
    local cx, cy, cz = center.x, center.y, center.z
    local nearby = {}
    local players = player.GetAll() -- connected players only (or player.GetHumans())

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) then
            local p = ply:GetPos()
            local dx = p.x - cx
            local dy = p.y - cy
            local dz = p.z - cz

            if dx * dx + dy * dy + dz * dz <= radiusSq then
                nearby[#nearby + 1] = ply
            end
        end
    end

    return nearby
end

-- usage
local near = playersWithinRadius(Vector(0, 0, 0), 500)
```
Reason: `ents.FindInSphere` is O(all entities), then filtering adds overhead, while this is O(players) and avoids `sqrt` by comparing squared distances so it stays cheap when only player proximity is needed.


```lua
local n = 1000000
local total = 0

for i = 1, n do
    total = total + 1
end
```
Reason: Use a numeric `for` loop for a tight counter loop, because Garry's Mod Lua handles the bounds/step in the loop machinery, which is generally lower-overhead than manually incrementing and checking in an equivalent `while` loop.


```lua
-- Faster: one hook dispatch per tick, iterate players once inside the hook.
local TICK_HOOK = "MyAddon_PlayerTick"

local function DispatchPlayerTick()
    local players = player.GetAll()
    hook.Run(TICK_HOOK, players, FrameTime())
end
hook.Add("Think", "MyAddon_DispatchPlayerTick", DispatchPlayerTick)

hook.Add(TICK_HOOK, "MyAddon_PlayerLogic", function(players, dt)
    for _, ply in ipairs(players) do
        if not IsValid(ply) then
            continue
        end

        -- custom per-player logic here
    end
end)

-- Slower alternative (N hook.Run calls):
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run(TICK_HOOK, ply, FrameTime())
-- end
```
Reason: One `hook.Run` per tick avoids repeated hook lookup/dispatch overhead and reduces call overhead from O(N) `hook.Run` calls to O(N) logic inside a single callback where work is already required.


```lua
hook.Add("HUDPaint", "FastHealthHUD", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end

    local hp = ply:Health()
    local x, y = 16, 16

    draw.RoundedBox(0, x, y, 180, 50, Color(0, 0, 0, 150))
    draw.RoundedBox(0, x + 4, y + 26, math.max(0, hp), 16, Color(220, 30, 30, 220))
    draw.SimpleText("HP: " .. hp, "DermaLarge", x + 90, y + 14, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end)
```
Reason: Cache `LocalPlayer()` and the `Health()` result in locals once per frame, then reuse that value in all three draw calls instead of calling `LocalPlayer():Health()` repeatedly.


```lua
local WHITE = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "FastPaint", function()
    surface.SetDrawColor(WHITE) -- set once, reused for all draws

    for i = 1, 200 do
        local x = (i - 1) * 8
        surface.DrawRect(x, 8, 6, 6)
    end
end)
```
Reason: `Color(255,255,255)` is created each iteration today, so cache the `Color` once and move `SetDrawColor` out of the inner loop to remove repeated allocations and reduce per-item calls.


```lua
local sin = math.sin  -- cache function once, outside the hot path

local sum = 0
for i = 1, 100000 do
    local a = i * 0.01
    sum = sum + sin(a)
end
```
Reason: Caching `math.sin` in a local (`sin`) avoids repeated global table lookup and method resolution each iteration in a hot loop.


```lua
local cachedLocalPlayer

local function GetLocalPlayer()
    if not IsValid(cachedLocalPlayer) then
        cachedLocalPlayer = LocalPlayer()
    end
    return cachedLocalPlayer
end

hook.Add("Think", "MyAddon_FastLocalPlayerLoop", function()
    local lp = GetLocalPlayer()
    if not IsValid(lp) then return end

    -- use lp repeatedly here without calling LocalPlayer() again
    lp:SetEyeAngles(lp:EyeAngles())
end)

hook.Add("ShutDown", "MyAddon_ClearLocalPlayerCache", function()
    cachedLocalPlayer = nil
end)
```
Reason: Cache the client player in a local variable and only refresh it when it becomes invalid, so high-frequency code reads `cachedLocalPlayer` instead of performing a global `LocalPlayer()` lookup each call.


```lua
local COS_FACING = math.cos(math.rad(22.5)) -- ~22.5° cone

local function ArePlayersLookingAtEachOther(plyA, plyB)
    if not IsValid(plyA) or not IsValid(plyB) then
        return false
    end

    local dirAtoB = plyB:EyePos() - plyA:EyePos()
    if dirAtoB:LengthSqr() == 0 then
        return false
    end

    dirAtoB:Normalize() -- one normalization only

    return plyA:GetAimVector():Dot(dirAtoB) >= COS_FACING
        and plyB:GetAimVector():Dot(-dirAtoB) >= COS_FACING
end
```
Reason: Dot product gives cosine of the angle to the target direction, so using precomputed `cos(theta)` thresholds checks “roughly facing” without expensive `acos` or angle math.


```lua
SomeHelper(ply)
```
Reason: `:` is just sugar for `obj:method(...)` -> `obj.method(obj, ...)`, so for your own helper that just takes a player parameter, explicit `SomeHelper(ply)` is typically the clearer and slightly faster option (one direct lookup) unless you need a true method attached to the object.


```lua
local DEBUG = true
local TAG = "[DBG] "

local function hotDebug(frame, hp)
    if not DEBUG then return end
    MsgN(TAG, "frame=", frame, " hp=", hp)
end

-- called from hot path
hotDebug(CurTime(), player:Health())
```
Reason: `MsgN` is a faster console writer in Garry's Mod than `print`, because `print` does extra formatting/spacing work and `MsgN` writes directly to the console with variadic output plus a newline.


```lua
local n = #arr
for i = 1, n do
    local v = arr[i]
    -- use v
end
```
Reason: Numeric `for` over `1..#arr` is the fastest for dense array-like tables in Lua because it does direct integer indexing in a compiled loop with a single length check, while `ipairs`/`pairs` use iterator machinery and extra dispatch overhead.


```lua
local TEAM_POLICE = TEAM_POLICE

local function policeNamesWithMoney(minSalary)
    local players = player.GetAll()
    local out = {}
    local outN = 0

    for i = 1, #players do
        local ply = players[i]

        if ply:Alive() and ply:Team() == TEAM_POLICE then
            local salary = ply:getDarkRPVar("salary") or 0
            if salary > minSalary then
                outN = outN + 1
                out[outN] = ply:Nick()
            end
        end
    end

    return out
end

local names = policeNamesWithMoney(500)
```
Reason: This is a single pass filter/map loop (alive + team + salary filter, then map to `Nick()`), which is faster than `fn` pipelines because it avoids nested iterator/combinator calls and intermediate tables per stage.


```lua
local cachedPlayers = {}
local playerSlotByEnt = {}

local function cachePlayerAdd(ply)
    local ent = ply:EntIndex()
    if playerSlotByEnt[ent] then return end

    local slot = #cachedPlayers + 1
    cachedPlayers[slot] = ply
    playerSlotByEnt[ent] = slot
end

local function cachePlayerRemove(ply)
    local ent = ply:EntIndex()
    local slot = playerSlotByEnt[ent]
    if not slot then return end

    local lastSlot = #cachedPlayers
    local lastPly = cachedPlayers[lastSlot]

    cachedPlayers[slot] = lastPly
    playerSlotByEnt[lastPly:EntIndex()] = slot

    cachedPlayers[lastSlot] = nil
    playerSlotByEnt[ent] = nil
end

hook.Add("Initialize", "PlayerCache_Init", function()
    for _, ply in ipairs(player.GetAll()) do
        cachePlayerAdd(ply)
    end
end)

hook.Add("PlayerInitialSpawn", "PlayerCache_Add", function(ply)
    cachePlayerAdd(ply)
end)

hook.Add("PlayerDisconnected", "PlayerCache_Remove", function(ply)
    cachePlayerRemove(ply)
end)

hook.Add("Think", "PlayerTick_CachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        -- per-tick work using cached player list
    end
end)
```
Reason: This replaces per-tick `player.GetAll()` scans with O(1)-update cache maintenance on join/leave hooks, so the tick loop only iterates a maintained table.


```lua
local plyState = {} -- key by EntIndex, value = plain Lua table

local function getState(ply)
    local id = ply:EntIndex()
    local s = plyState[id]
    if s == nil then
        s = {}
        plyState[id] = s
    end
    return s
end

hook.Add("PlayerSpawn", "InitPlyState", function(ply)
    local s = getState(ply)
    s.score = 0
    s.lastShot = 0
end)

hook.Add("PlayerDisconnected", "CleanupPlyState", function(ply)
    plyState[ply:EntIndex()] = nil
end)

-- hot path read
local function updatePlayer(ply)
    local s = plyState[ply:EntIndex()] -- one direct table lookup
    if s and s.score > 0 then
        s.lastShot = CurTime()
    end
end
```
Reason: keying per-player temp data in a session-local table (numeric entity index -> data table) replaces repeated `ply.someField` entity-metatable lookups with a single cheap table lookup, which is faster for very frequent reads.


```lua
-- Faster for fixed-size iteration: dense numeric array
local actions = {"move", "attack", "reload", "jump"}

for i = 1, #actions do
    local action = actions[i]
    print(i, action)
end

-- String-keyed map (slower for same fixed collection)
local actionMap = {
    move = "move",
    attack = "attack",
    reload = "reload",
    jump = "jump"
}

for _, action in pairs(actionMap) do
    print(action)
end
```
Reason: In Garry's Mod Lua, iterating a fixed collection is faster with a contiguous 1-based numeric array (`for i=1,#t`/`ipairs`) because it hits LuaJIT's array storage path and avoids hash lookups and unordered traversal from string-keyed maps.


```lua
local setColor = surface.SetDrawColor
local r, g, b, a = 40, 120, 255, 255

hook.Add("HUDPaint", "FastDraw", function()
    for i = 1, 120 do
        setColor(r, g, b, a) -- fastest in hot loops
        surface.DrawRect(10, i * 2, 200, 2)
    end
end)
```
Reason: Passing `r,g,b,a` directly avoids per-call Color table/object handling and field lookups, which is cheaper for high-frequency draw paths.


```lua
local steamID = player:SteamID()
local coins = sql.QueryValue("SELECT coins FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
```
Reason: For one Garry's Mod server with no cross-server sync, local SQLite is typically lower latency than remote MySQL because it avoids network round-trips and stays in-process on the same machine.


```lua
local steamIDCache = setmetatable({}, { __mode = "k" })

local function GetCachedSteamID(ply)
    if not IsValid(ply) then return nil end

    local sid = steamIDCache[ply]
    if sid ~= nil then
        return sid
    end

    sid = ply:SteamID()
    steamIDCache[ply] = sid
    return sid
end

hook.Add("PlayerInitialSpawn", "steamid_cache_prime", function(ply)
    steamIDCache[ply] = ply:SteamID()
end)

hook.Add("PlayerDisconnected", "steamid_cache_clear", function(ply)
    steamIDCache[ply] = nil
end)

hook.Add("EntityRemoved", "steamid_cache_clear_removed", function(ent)
    if ent:IsPlayer() then
        steamIDCache[ent] = nil
    end
end)
```
Reason: Cache SteamID once per player and reuse it in hot loops via table lookup, eliminating repeated `ply:SteamID()` calls and reducing per-tick overhead while clearing cache on lifecycle changes to avoid stale/leaked entries.


```lua
local pieces = {}
for i = 1, 5000 do
    pieces[i] = "piece" .. i .. ", "
end

-- Slow/avoid: repeated concatenation in a loop
local function slow_concat(t)
    local s = ""
    for i = 1, #t do
        s = s .. t[i]
    end
    return s
end

-- Fast: buffer chunks then concatenate once
local function fast_concat(t)
    local buf = {}
    local n = 0
    for i = 1, #t do
        n = n + 1
        buf[n] = t[i]
    end
    return table.concat(buf)
end

local big = fast_concat(pieces)
```
Reason: In GMod Lua, repeated `..` in a loop repeatedly grows and copies the whole string, while collecting fragments in a table and calling `table.concat` once performs linear work and is much faster for thousands of pieces.


```lua
-- Faster solid non-rounded rectangle draw in Garry's Mod client Lua
hook.Add("HUDPaint", "FastRects", function()
    surface.SetDrawColor(255, 180, 40, 255)
    surface.DrawRect(16, 16, 280, 40)
    surface.DrawRect(16, 64, 280, 40)
end)
```
Reason: `surface.DrawRect` renders a plain filled rectangle directly, while `draw.RoundedBox(0, ...)` still routes through rounded-box logic that does extra work even at zero radius.


```lua
-- one-time font setup
surface.CreateFont("PerfSingleLine", {
    font = "Roboto",
    size = 20,
    weight = 600,
    antialias = true
})

local text = "FPS: "
local x, y = 16, 16
local col = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("PerfSingleLine")
    surface.SetTextColor(col)
    surface.SetTextPos(x, y)
    surface.DrawText(text .. math.floor(SysTime() * 1000))
end)
```
Reason: `surface.SetFont` + `surface.SetTextColor` + `surface.SetTextPos` + `surface.DrawText` is faster than `draw.DrawText`/`SimpleTextOutlined` because it avoids wrapper overhead (alignment logic, optional size queries, and extra outline passes).


```lua
local arr = {10, 20, 30}
local n = #arr
print(n) -- 3
```
Reason: Use the length operator `#` (`#arr`) for a sequential, array-like table in Garry's Mod Lua.


```lua
-- Fastest when you can replace the table reference
t = {}
```
Reason: In Garry's Mod Lua `table.Empty(t)` is O(n) because it iterates and nils each key, while `t = {}` is usually O(1), so reassigning to a fresh table is faster for large sequential tables when old references are not required.


```lua
local list = {"weapon_crowbar", "weapon_pistol", "weapon_smg1", "weapon_ar2"}

-- Faster set/prepared hash table
local weaponSet = {}
for _, v in ipairs(list) do
    weaponSet[v] = true
end

-- O(1)
local function HasWeapon(name)
    return weaponSet[name] == true
end

-- Slower legacy style (O(n), each call scans)
-- local slow = table.HasValue(list, "weapon_pistol")

if HasWeapon("weapon_pistol") then
    print("has weapon")
end
```
Reason: Precompute a set-like table (`set[value] = true`) and test membership with `set[val]`, so repeated checks are constant-time instead of repeatedly scanning the list with `table.HasValue`.


```lua
-- Faster: construct once with known fields
local actor = {
    name = "gman",
    health = 100,
    armor = 50,
}

-- Slower: extra table writes after creation
local actorSlow = {}
actorSlow.name = "gman"
actorSlow.health = 100
actorSlow.armor = 50
```
Reason: Use the constructor form, because it performs one table creation + literal field setup in one expression instead of multiple post-creation assignment operations.


```lua
local rand = math.random

local function randomFromSequential(t)
    local n = #t
    return n > 0 and t[rand(n)] or nil
end
```
Reason: Direct integer indexing (`t[math.random(n)]`) uses O(1) array access and avoids `table.Random`'s generic non-sequential-table handling.


```lua
local acc = 0
for i = 1, #values do
    local x = values[i]
    acc = acc + x * x
end
```
Reason: `x * x` is direct multiplication (no function lookup or call overhead), which is the fastest way to square in Lua hot loops.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- process each connected player
end
```
Reason: `player.GetAll()` returns all currently connected players, and iterating it with `ipairs` visits each player once in a concise modern Lua loop.