```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the extra `draw.RoundedBox` wrapper work when the corner radius is `0`.


```lua
local text = "Fast HUD text"
local font = "Trebuchet24"
local x, y = 32, 32
local color = Color(255, 255, 255)

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(color)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` avoids the extra wrapping, alignment, and outline work in `draw.DrawText` / `draw.SimpleTextOutlined`, so it is the faster path for one single-line string drawn every frame.


```lua
local length = #items
```
Reason: Use Lua's `#` length operator for sequential array-like tables; `table.Count` is for counting key/value pairs.


```lua
t = {}
```
Reason: Rebinding creates a fresh empty table in constant time, while table.Empty(t) has to remove the existing entries; use table.Empty only when other references must keep seeing the same table.


```lua
-- Slower: linear scan through a list
local allowedTeams = { "citizen", "police", "medic" }
if table.HasValue(allowedTeams, teamName) then
    -- allowed
end

-- Faster: use a set and check the key directly
local allowedTeamsSet = {
    citizen = true,
    police = true,
    medic = true,
}

if allowedTeamsSet[teamName] then
    -- allowed
end
```
Reason: `table.HasValue` scans every list item, while a set lookup uses direct table indexing.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: The table constructor is faster because Lua creates and initializes the known fields in one operation instead of creating an empty table and performing separate field assignments.


```lua
local items = { "a", "b", "c", "d" }

local value = items[math.random(#items)]
```
Reason: For a sequential table, direct numeric indexing avoids table.Random's generic table traversal/key handling.


```lua
local squared = x * x
```
Reason: Multiplication avoids the slower exponent operator and is the preferred fast form for squaring in a tight loop.


Uses player.Iterator() (wiki-recommended Lua-cached iterator).

```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: player.Iterator() visits connected players directly without building the player.GetAll() table first.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, avoiding `ents.GetAll()` and its full-map entity table.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers the callback on the `Think` hook using `MyAddon.Think` as its unique identifier.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` safely rejects nil, NULL, or removed entity references before you call entity methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Read message data here.
end)
```
Reason: net.Receive registers the callback for incoming MyAddon.Sync messages.


```lua
local ZERO_ANGLE = Angle(0, 0, 0)

local function FreshZeroAngle()
    return ZERO_ANGLE * 1
end
```
Reason: multiplying a cached zero Angle returns a fresh Angle copy and avoids the slower constructor call in the hot path.


```lua
local configColor = Color(255, 80, 80)

local color = configColor
```
Reason: A local variable read is faster than chained table lookups like `myaddon.config.color`, especially in hot paths.


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

-- Avoid for DarkRP job names
local jobNameFromNW = ply:GetNWString("job")
```
Reason: DarkRP owns job state through DarkRPVars, so getDarkRPVar("job") reads the correct DarkRP value instead of raw NWString data.


```lua
local maxDist = 250

if posA:DistToSqr(posB) <= maxDist * maxDist then
    -- within threshold
end
```
Reason: DistToSqr compares squared distance, avoiding the square root needed for actual distance.


Answer must contain 1 through 1 candidate loops.

```lua
if ents.Iterator then
    for _, ent in ents.Iterator() do
        -- use ent
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- use ent
    end
end
```
Reason: ents.Iterator avoids building the ents.GetAll table when available; the fallback keeps compatibility with older Garry's Mod builds.


```lua
local function FindNearbyEntitiesCheap(ply, radius)
    local pos = ply:GetPos()
    local half = Vector(radius, radius, radius)

    return ents.FindInBox(pos - half, pos + half)
end
```
Reason: `ents.FindInBox` is a fast built-in spatial-partition query in common GMod benchmarks, and it is cheaper than doing broad Lua-side scans when an AABB around the player is good enough.


```lua
local function FindPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local found = {}
    local count = 0

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

    return found
end
```
Reason: `player.GetAll()` scans only players and `DistToSqr` avoids the square root and entity table/filter cost of `ents.FindInSphere`.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` is generally faster for tight 1-to-n counting in Garry's Mod Lua because it uses the VM/JIT's specialized loop path instead of manual `while` condition and increment work.


```lua
-- Faster: one hook dispatch per tick, with all players passed once.
hook.Add("Think", "NotifyPlayerTickBatch", function()
    hook.Run("MyAddon_PlayerTickBatch", player.GetAll())
end)

hook.Add("MyAddon_PlayerTickBatch", "CustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom logic for ply
    end
end)

-- Slower: one hook dispatch per player per tick.
-- hook.Add("Think", "NotifyPlayerTickPerPlayer", function()
--     local players = player.GetAll()
--     for i = 1, #players do
--         hook.Run("MyAddon_PlayerTick", players[i])
--     end
-- end)
```
Reason: One `hook.Run` keeps the same per-player work but avoids multiplying hook lookup and dispatch overhead by player count every tick.


```lua
local ply = LocalPlayer()
local health = ply:Health()

draw.SimpleText(health, "DermaLarge", 32, 32, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.SimpleText("HP: " .. health, "DermaDefaultBold", 32, 64, Color(220, 80, 80), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.RoundedBox(4, 32, 88, math.Clamp(health, 0, 100) * 2, 14, Color(220, 80, 80))
```
Reason: LocalPlayer() and Health() are called once, then the cached value is reused for all three draw calls in the same HUDPaint frame.


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

hook.Add("HUDPaint", "FastPaintExample", function()
    for i = 1, #items do
        draw.SimpleText(items[i].text, "DermaDefault", items[i].x, items[i].y, WHITE)
    end
end)
```
Reason: Create the Color table once outside the paint loop and reuse it, avoiding per-frame allocations and GC work.


```lua
local sin = math.sin

for i = 1, count do
    total = total + sin(i)
end
```
Reason: Localizing `math.sin` once avoids repeated global/table lookups inside the hot loop.


```lua
local cachedLocalPlayer

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

    return cachedLocalPlayer
end

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

    -- Use ply in hot code instead of calling LocalPlayer() repeatedly.
end)
```
Reason: Reusing a cached local entity avoids repeated global LocalPlayer lookups and function calls while still refreshing until the player is valid.


```lua
local LOOK_DOT = 0.75 -- cosine threshold; higher is stricter

local function RoughlyLookingAtEachOther(a, b, dotLimit)
    if not IsValid(a) or not IsValid(b) then return false end

    dotLimit = dotLimit or LOOK_DOT

    local aToB = (b:EyePos() - a:EyePos()):GetNormalized()
    local bToA = -aToB

    return a:GetAimVector():Dot(aToB) >= dotLimit
       and b:GetAimVector():Dot(bToA) >= dotLimit
end
```
Reason: Dot products compare against a cosine threshold directly, avoiding expensive `math.acos` angle conversion while still checking both aim vectors face the other player.


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

SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster for a helper you control because a local function call avoids the `:` method/metatable lookup on `ply`.


```lua
local DEBUG_HOT_PATH = true

if DEBUG_HOT_PATH then
    MsgN("[my_addon] hot path reached")
end
```
Reason: `MsgN` writes directly to the console with a newline and avoids the extra work `print` does around formatting multiple values.


```lua
local sum = 0
local nums = numbers

for i = 1, #nums do
    sum = sum + nums[i]
end
```
Reason: A numeric `for` over integer indexes avoids iterator calls and key/value traversal overhead, so it is typically fastest for large dense sequential arrays in Garry's Mod Lua.


```lua
local function richAlivePlayerNames(players, minMoney)
    local out, outN = {}, 0

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:Alive() then
            local money = ply:getDarkRPVar("money") or 0
            if money >= minMoney then
                outN = outN + 1
                out[outN] = ply:Nick()
            end
        end
    end

    return out
end
```
Reason: Fuse filter and map into one numeric `for` loop, avoiding DarkRP `fn` closure calls and intermediate tables.


```lua
if SERVER then
    local cachedPlayers = {}

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

    hook.Add("InitPostEntity", "MyAddon.RefreshPlayerCache", RefreshPlayerCache)
    hook.Add("PlayerInitialSpawn", "MyAddon.RefreshPlayerCache", RefreshPlayerCache)
    hook.Add("PlayerDisconnected", "MyAddon.RefreshPlayerCache", function()
        timer.Simple(0, RefreshPlayerCache) -- let the leaving player be removed first
    end)

    hook.Add("Think", "MyAddon.FastPlayerThink", function()
        for i = 1, #cachedPlayers do
            local ply = cachedPlayers[i]
            if IsValid(ply) then
                -- per-player work here
            end
        end
    end)
end
```
Reason: `player.GetAll()` allocates/builds work only on join/leave, while the hot `Think` path only walks the already-cached table with a numeric loop.


```lua
local hotData = {}

local function SetHotValue(ply, value)
    hotData[ply] = value
end

local function GetHotValue(ply)
    return hotData[ply]
end

hook.Add("PlayerDisconnected", "ClearHotData", function(ply)
    hotData[ply] = nil
end)
```
Reason: A local side table avoids repeated Player entity field lookup/metatable work, so hot reads use a plain Lua table access.


```lua
local values = {
    "first",
    "second",
    "third",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays iterate faster than string-keyed maps because contiguous numeric slots avoid per-entry string-key hashing.


```lua
local drawR, drawG, drawB, drawA = 40, 160, 255, 220

hook.Add("HUDPaint", "HotPathDraw", function()
    surface.SetDrawColor(drawR, drawG, drawB, drawA)
    surface.DrawRect(16, 16, 160, 8)
end)
```
Reason: Passing separate r, g, b, a numbers avoids the Color table path and is faster in hot draw code.


```lua
local steamID64 = ply:SteamID64()
local row = sql.QueryRow((
    "SELECT money, xp FROM player_data WHERE steamid64 = %s LIMIT 1"
):format(sql.SQLStr(steamID64)))
```
Reason: Local SQLite via Garry's Mod's `sql` library avoids network round trips, so on a single server with no sync requirement it is typically lower latency than remote MySQL.


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

local function CachedSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID ~= nil then
        return steamID
    end

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

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

-- Hot path:
local steamID = CachedSteamID(ply)
```
Reason: This pays the `ply:SteamID()` call once per player, then uses a fast table lookup while weak keys and disconnect cleanup avoid stale player entries.


Answer must contain 0 through 0 candidate loops.

```lua
local pieces = {"alpha", "beta", "gamma"} -- thousands of small strings

-- Slower: creates a new string on every iteration.
local slow = ""
for i = 1, #pieces do
    slow = slow .. pieces[i]
end

-- Faster: collect pieces, then join once.
local buffer = {}
for i = 1, #pieces do
    buffer[#buffer + 1] = pieces[i]
end

local fast = table.concat(buffer)
```
Reason: `table.concat` avoids thousands of intermediate string allocations from repeated `..` concatenation.


```lua
surface.SetDrawColor(col)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect draws the plain rectangle directly, avoiding draw.RoundedBox's rounded-box wrapper overhead when radius is 0.


```lua
local text = "Fast HUD text"
local font = "DermaDefault"
local x, y = 32, 32

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 lower-level fast path for one line; it avoids the extra wrapping, alignment, and outline passes done by `draw.DrawText` / `draw.SimpleTextOutlined`.


```lua
local length = #myTable
```
Reason: The # operator is preferred for sequential array-like tables because it gets the array length directly; table.Count is for keyed/non-sequential tables.


```lua
t = {}
```
Reason: Replacing the table drops the old large array for GC instead of walking and clearing every element; use `table.Empty(t)` only when other references must keep seeing the same table.


```lua
-- Slow: table.HasValue scans the list every time.
-- if table.HasValue({ "weapon_physgun", "weapon_crowbar", "weapon_pistol" }, class) then ... end

-- Fast: use a keyed set for direct lookup.
local allowedWeapons = {
    weapon_physgun = true,
    weapon_crowbar = true,
    weapon_pistol = true,
}

hook.Add("PlayerCanPickupWeapon", "AllowedWeaponSetLookup", function(ply, weapon)
    return allowedWeapons[weapon:GetClass()] == true
end)
```
Reason: A keyed set lookup is O(1) average time, while table.HasValue scans the list in O(n) time for every check.


```lua
local info = {
    steamID = steamID,
    name = name,
    score = score,
}
```
Reason: The table constructor lets Lua create the table with the known fields up front, avoiding extra field-assignment bytecode after `{}`.


```lua
local value = items[math.random(#items)]
```
Reason: For a sequential table, direct numeric indexing avoids `table.Random` walking/counting table entries and only needs one random index lookup.


```lua
local squared = x * x
```
Reason: `x * x` avoids exponentiation overhead and is the preferred fast form for squaring in tight loops.


```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` iterates the current connected player list directly without building and walking a `player.GetAll()` table.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- do work with ent
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, so it avoids materializing a table of every entity in the map first.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a function on the `Think` hook using `MyAddon.Think` as the unique identifier.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that rejects `nil`, NULL entities, and removed invalid entities before method calls.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` registers a callback for the incoming `MyAddon.Sync` net message.


```lua
local ZERO_ANGLE = Angle(0, 0, 0)

-- Hot path: reuse the shared zero angle instead of constructing Angle() each time.
entity:SetAngles(ZERO_ANGLE)
```
Reason: Reusing one prebuilt zero `Angle` avoids per-call object construction and garbage pressure in hot paths.


```lua
local MYADDON_COLOR = "red"

local color = MYADDON_COLOR
```
Reason: A flat local is preferred because local variable reads avoid repeated table indexing and are the fastest common access path in Lua for hot settings reads.


```lua
-- Preferred
local jobName = team.GetName(ply:Team())

-- Avoid
local jobNameOld = ply:GetNWString("job")
```
Reason: `team.GetName(ply:Team())` reads the authoritative team/job state directly, while `GetNWString("job")` depends on a networked string that is less direct and can be stale or overridden.


```lua
if pos1:DistToSqr(pos2) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root from `Distance`, so it is the preferred faster check when you only need a threshold comparison.


```lua
for ent in ents.Iterator() do
    -- use ent
end
```
Reason: `ents.Iterator()` visits every entity without first building the full table from `ents.GetAll()`, so it is the efficient wiki-recommended choice when you only need to iterate once.


```lua
local center = ply:GetPos()
local radius = 512
local nearby = ents.FindInSphere(center, radius)

for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a common fast built-in for cheap nearby-entity queries around a player without relying on PVS visibility.


```lua
local function FindPlayersInRadius(pos, radius)
    local players = player.GetAll()
    local result = {}
    local radiusSqr = radius * radius

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

        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            result[#result + 1] = ply
        end
    end

    return result
end
```
Reason: `ents.FindInSphere` checks all entities, while iterating `player.GetAll()` limits the search to players only and uses squared distance to avoid the square root cost.


```lua
for i = 1, n do
    -- hot loop body
end
```
Reason: Numeric `for` is generally faster in Garry's Mod Lua because it uses the VM's specialized counting-loop path with less per-iteration overhead than a manual `while` counter loop.


Answer must contain 0 through 1 candidate loops.

```lua
local players = player.GetHumans()

hook.Run("MyPlayersTick", players)

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

-- Slower pattern:
for i = 1, #players do
    hook.Run("MyPlayerTick", players[i])
end
```
Reason: Calling `hook.Run` once avoids repeated hook dispatch overhead, argument setup, and multiple global hook traversals, so one dispatch with an internal player loop is faster than one dispatch per player.


```lua
local hp = LocalPlayer():Health()

draw.SimpleText(hp, "DermaLarge", x1, y1, color_white)
draw.RoundedBox(4, x2, y2, math.max(hp, 0) * 2, 20, color_green)
draw.SimpleText(hp .. "%", "Trebuchet24", x3, y3, color_white)
```
Reason: Cache `LocalPlayer():Health()` once per frame to avoid three repeated Lua/C++ calls for the same value.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(WHITE)

    for i = 1, self.ItemCount do
        -- draw using WHITE without allocating a new Color each iteration
    end
end
```
Reason: Reuse one precomputed `Color` object so the paint loop avoids repeated allocation and function-call overhead each frame.


```lua
local sin = math.sin

for i = 1, n do
    out[i] = sin(i * step)
end
```
Reason: Caching `math.sin` in a local avoids repeated table lookups in the hot loop, which is slightly faster in Lua.


```lua
local localPlayer

hook.Add("InitPostEntity", "CacheLocalPlayer", function()
    localPlayer = LocalPlayer()
end)

hook.Add("Think", "UseCachedLocalPlayer", function()
    local ply = localPlayer
    if not IsValid(ply) then
        ply = LocalPlayer()
        if not IsValid(ply) then return end
        localPlayer = ply
    end

    -- use ply here instead of calling LocalPlayer() repeatedly
    if ply:Alive() then
        -- hot-path work
    end
end)
```
Reason: Cache the player entity once and reuse a local variable on hot paths, only refreshing when the cached value is invalid, which avoids repeated global function lookup and call overhead.


```lua
local LOOK_DOT_THRESHOLD = -0.7 -- closer to -1 means more directly facing each other

local function ArePlayersRoughlyLookingAtEachOther(plyA, plyB)
    local aimA = plyA:GetAimVector()
    local aimB = plyB:GetAimVector()

    -- Unit vectors: dot is enough, no acos needed.
    return aimA:Dot(aimB) <= LOOK_DOT_THRESHOLD
end
```
Reason: `GetAimVector()` returns normalized directions, so a single dot-product compare is the cheapest fast-path; facing each other means the vectors point in near-opposite directions, which drives the dot toward `-1` without the cost of `math.acos`.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster for a helper you control because it can be a direct local/global function call and avoids the extra table/metatable method lookup implied by `ply:SomeHelper()`.


```lua
MsgN("debug: cache hit")
```
Reason: `MsgN` writes directly to the console with a newline and avoids some of `print`'s extra formatting overhead, so it is the usual faster choice in a hot path.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: For a large dense array, numeric `for` is typically fastest because it avoids the extra iterator overhead of `pairs` and `ipairs` and does direct indexed access.


```lua
-- Faster than chaining DarkRP's fn combinators: one tight pass, no closure pipeline,
-- no intermediate tables from filter/map steps.
local players = player.GetAll()
local out = {}
local n = 0

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

    if IsValid(ply) and ply:Alive() and ply:isCP() then
        n = n + 1
        out[n] = {
            steamID = ply:SteamID(),
            money = ply:getDarkRPVar("money") or 0,
        }
    end
end

return out
```
Reason: A single fused `for` loop avoids the extra closures, function-call overhead, and intermediate table allocations that DarkRP's `fn` filter/map chain creates.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "RefreshCachedPlayers", refreshPlayers)
hook.Add("PlayerDisconnected", "RefreshCachedPlayers", refreshPlayers)
hook.Add("InitPostEntity", "RefreshCachedPlayersOnStart", refreshPlayers)

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- per-player work here
        end
    end
end)
```
Reason: `player.GetAll()` allocates/builds a fresh player array every tick, so caching it and only refreshing on join/leave removes repeated table creation and iteration setup from the hot path.


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

local function SetTempHP(ply, value)
    hpByPlayer[ply] = value
end

local function GetTempHP(ply)
    return hpByPlayer[ply]
end
```
Reason: A side table avoids adding dynamic fields to the player entity userdata/table, so repeated lookups stay on a plain Lua table path and are typically faster for hot reads.


```lua
local values = { "alpha", "beta", "gamma", "delta" }
for i = 1, #values do
    local v = values[i]
    -- use v
end
```
Reason: Sequential number-indexed arrays are faster to iterate in Garry's Mod Lua because dense numeric indexing avoids string-hash lookups and works with the VM's optimized array-style traversal path.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing raw numeric channels is faster in a hot draw path because it avoids the extra Color table/object handling overhead.


```lua
local result = sql.Query("SELECT money FROM players WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: For one Garry's Mod server with no cross-server sync, local SQLite via `sql` is typically lower latency because it avoids network round trips to a remote MySQL server.


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

local function getSteamID(ply)
    local steamId = steamIdCache[ply]
    if steamId ~= nil then
        return steamId
    end

    steamId = ply:SteamID()
    steamIdCache[ply] = steamId
    return steamId
end

hook.Add("EntityRemoved", "ClearSteamIDCache", function(ent)
    steamIdCache[ent] = nil
end)

-- hot path
for i = 1, #players do
    local ply = players[i]
    local steamId = getSteamID(ply)
    -- use steamId
end
```
Reason: It avoids repeated method calls on the same player in the hot path, computes the SteamID once per live player, and uses weak keys so cache entries can disappear when player entities do.


```lua
local parts = {}

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

local big = table.concat(parts)

-- slower:
-- local big = ""
-- for i = 1, 10000 do
--     big = big .. "piece" .. i
-- end
```
Reason: `table.concat` avoids reallocating and copying the growing string on every loop iteration, so it is much faster for thousands of pieces.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` adds wrapper overhead, while `surface.DrawRect` is the direct non-rounded rectangle draw path and is slightly faster in tight per-frame loops.


```lua
local text = "FPS: 144"
local x, y = 24, 24
local r, g, b, a = 255, 255, 255, 255

surface.CreateFont("BenchText", {
    font = "Tahoma",
    size = 24,
    weight = 500,
    antialias = true,
})

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("BenchText")
    surface.SetTextColor(r, g, b, a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextColor` + `surface.SetTextPos` + `surface.DrawText` is the leanest path for single-line text; `draw.DrawText` and especially `draw.SimpleTextOutlined` add wrapper work such as alignment, color/state setup, and outline passes.


```lua
local len = #t
```
Reason: `#` is the idiomatic and fastest way to get the length of a proper sequential array-like table in Garry's Mod Lua.


```lua
local t = {}
```
Reason: Rebinding with `t = {}` is generally faster because it avoids walking and niling every element the way `table.Empty(t)` does; use `table.Empty(t)` only when other references must keep the same table object.


```lua
local allowed = {
    pistol = true,
    shotgun = true,
    smg1 = true,
}

if allowed[weaponClass] then
    -- value exists in the set
end

-- slower on a list:
-- table.HasValue({"pistol", "shotgun", "smg1"}, weaponClass)
```
Reason: Hash lookup in a key->true set is O(1) on average, while `table.HasValue` scans the list linearly at O(n).


```lua
local t1 = {}
t1.x = 1
t1.y = 2
t1.z = 3

local t2 = { x = 1, y = 2, z = 3 }
```
Reason: `local t2 = { x = 1, y = 2, z = 3 }` is generally faster for a small table with known fields because Lua can create and populate it in one constructor step instead of doing separate field assignments after allocation.


```lua
local t = {"a", "b", "c", "d"}
local value = t[math.random(#t)]
```
Reason: For a sequential array, direct indexing with `math.random(#t)` avoids the extra work `table.Random` does to handle non-sequential tables.


```lua
local x2 = x * x
```
Reason: `x * x` avoids function-call overhead and is the straightforward fast form for squaring in a tight loop.


```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` iterates connected players directly without allocating the table from `player.GetAll()`.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities directly instead of allocating a full table like `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- per-frame logic
end)
```
Reason: `hook.Add` registers a callback on the `Think` hook, and `MyAddon.Think` is the unique identifier for that registration.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that the entity reference is non-`nil` and not a removed/invalid entity before you call methods on it.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Read the payload here with net.Read* functions.
end)
```
Reason: `net.Receive` registers the callback that runs when the `MyAddon.Sync` net message arrives.


```lua
local scratchAng = Angle(0, 0, 0)

-- Hot path: reuse and reset instead of allocating Angle() every time.
local function GetZeroedScratchAngle()
    scratchAng:SetUnpacked(0, 0, 0)
    return scratchAng
end

-- Slower:
-- local ang = Angle()

-- Faster:
local ang = GetZeroedScratchAngle()
```
Reason: Reusing one scratch `Angle` avoids per-call allocation and garbage collection; resetting it with `SetUnpacked(0, 0, 0)` is cheaper than constructing `Angle()` in a hot path.


```lua
local MYADDON_COLOR = Color(255, 255, 255)
local color = MYADDON_COLOR
```
Reason: A flat local is faster for frequent reads because Lua avoids repeated table lookups like `myaddon.config.color` and accesses locals through cheaper direct slots.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: `job` is a DarkRP-managed variable, so `ply:getDarkRPVar("job")` is the correct API; `GetNWString("job")` bypasses DarkRP's intended access layer and is less reliable across implementations.


```lua
if pos1:DistToSqr(pos2) <= (maxDistance * maxDistance) then
    -- within maxDistance
end
```
Reason: `Vector:DistToSqr` avoids the square root in `Distance`, so it is the preferred method for threshold comparisons.


```lua
local iter = ents.Iterator and ents.Iterator() or ipairs(ents.GetAll())

for _, ent in iter do
    -- use ent
end
```
Reason: `ents.Iterator()` avoids materializing a full entity table and is the wiki-recommended efficient choice; the fallback keeps the loop working where it is unavailable.


```lua
local origin = ply:GetPos()
local radius = 512
local nearby = ents.FindInSphere(origin, radius)

for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) and ent ~= ply then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a common fast built-in for nearby-entity queries because it uses the engine's spatial partition directly and avoids scanning all entities.


```lua
local function FindPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local out = {}

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

    return out
end
```
Reason: `ents.FindInSphere` walks all entities first; looping `player.GetAll()` only checks players and uses squared distance to avoid the square root cost.


```lua
for i = 1, n do
    -- body
end
```
Reason: Numeric `for` is generally faster in Garry's Mod Lua because the VM has a specialized counted-loop path, while `while` needs manual increment and extra condition work each iteration.


```lua
local players = player.GetHumans()
hook.Run("MyPerTickPlayers", players)

hook.Add("MyPerTickPlayers", "MyLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom per-player logic here
    end
end)

-- Slower pattern:
-- for i = 1, #players do
--     hook.Run("MyPerTickPlayer", players[i])
-- end
```
Reason: Calling `hook.Run` once avoids repeated hook dispatch overhead, repeated vararg setup, and repeated listener lookup on every player each tick.


```lua
hook.Add("HUDPaint", "DrawHealth", function()
    local ply = LocalPlayer()
    local health = ply:Health()

    draw.SimpleText(health, "DermaLarge", 32, 32, color_white)
    draw.RoundedBox(4, 32, 72, health * 2, 20, Color(200, 50, 50))
    draw.SimpleText("HP: " .. health, "Trebuchet24", 32, 100, color_white)
end)
```
Reason: It computes `LocalPlayer()` and `Health()` once per frame, avoiding repeated client Lua calls in the same `HUDPaint` pass.


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

hook.Add("HUDPaint", "FastPaintExample", function()
    for i = 1, 1000 do
        surface.SetDrawColor(WHITE)
        -- draw work here
    end
end)
```
Reason: Cache the `Color` once outside the paint loop so the hot path reuses one object instead of allocating a new color every iteration.


```lua
local sin = math.sin

for i = 1, 1000000 do
    local y = sin(i)
    -- hot loop work
end
```
Reason: Caching `math.sin` in a local avoids repeated table lookups on `math` inside the hot loop, which is slightly faster in Lua.


```lua
local LocalPlayer = LocalPlayer

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

    local pos = ply:GetPos()
    local vel = ply:GetVelocity()

    -- use pos / vel / ply here
end)
```
Reason: Caching the global `LocalPlayer` function in a local and calling it once per scope avoids repeated global lookups and repeated player retrieval work.


```lua
local FACE_DOT_THRESHOLD = -0.85 -- closer to -1 means more directly facing each other

local function ArePlayersRoughlyLookingAtEachOther(plyA, plyB)
    local aimA = plyA:GetAimVector()
    local aimB = plyB:GetAimVector()

    return aimA:Dot(aimB) <= FACE_DOT_THRESHOLD
end
```
Reason: A dot product is the cheap cosine check you want here; opposite aim directions produce values near `-1`, so this avoids expensive angle conversion and `math.acos`.


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

SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally a bit faster for a helper you control because it avoids the method-style lookup/dispatch path of `ply:SomeHelper()` and keeps the helper as a direct local function call.


```lua
MsgN("hot path debug:", someValue)
```
Reason: `MsgN` avoids the extra formatting and vararg handling overhead of `print`, so it is the cheaper built-in choice for frequent debug console output in Garry's Mod Lua.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: `numeric for` is typically fastest for a large sequential array because it avoids the extra iterator overhead of `pairs` and `ipairs` and does direct indexed access.


```lua
local function collectRichWantedNames(players, minMoney)
    local out = {}
    local n = 0

    for i = 1, #players do
        local ply = players[i]
        if ply.wanted and ply.money >= minMoney then
            n = n + 1
            out[n] = ply:Nick()
        end
    end

    return out
end

-- Faster than chaining fn.Filter + fn.Map because it does the same work in one pass.
local names = collectRichWantedNames(player.GetAll(), 10000)
```
Reason: A hand-written single-pass loop avoids fn’s extra closures, function-call overhead, and intermediate tables, so the same filter+map pipeline runs with less allocation and lower per-item cost.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "RefreshPlayerCache", refreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCache", refreshPlayerCache)
hook.Add("InitPostEntity", "RefreshPlayerCacheOnStartup", refreshPlayerCache)

hook.Add("Think", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- hot-path per-player work here
        end
    end
end)
```
Reason: `player.GetAll()` allocates/builds a fresh player array, so caching it and only rebuilding on join/leave removes per-tick table creation and iteration setup from the hot path.


```lua
local staminaByEntIndex = {}

local function SetStamina(ply, value)
    staminaByEntIndex[ply:EntIndex()] = value
end

local function GetStamina(ply)
    return staminaByEntIndex[ply:EntIndex()]
end

hook.Add("EntityRemoved", "ClearStaminaCache", function(ent)
    if ent:IsPlayer() then
        staminaByEntIndex[ent:EntIndex()] = nil
    end
end)
```
Reason: A plain Lua side table keyed by `EntIndex()` avoids repeated userdata field/hash lookup on `ply`, so hot reads are cheaper and still O(1).


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because they avoid hash lookup and use Lua's optimized array part with cache-friendly numeric access.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw `r, g, b, a` numbers avoids the extra `Color` object/table path, so it is the faster call style in a hot draw loop.


```lua
local rows = sql.Query("SELECT money FROM players WHERE steamid = " .. sql.SQLStr(steamID))
```
Reason: Local SQLite via Garry's Mod's `sql` library is typically lower latency on a single server because it avoids network round trips and remote database overhead.


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

local function GetSteamIDCached(ply)
    local steamId = steamIdCache[ply]
    if steamId ~= nil then
        return steamId
    end

    steamId = ply:SteamID()
    steamIdCache[ply] = steamId
    return steamId
end

hook.Add("EntityRemoved", "ClearSteamIDCache", function(ent)
    steamIdCache[ent] = nil
end)

-- Hot path
for i = 1, #players do
    local ply = players[i]
    local steamId = GetSteamIDCached(ply)
    -- use steamId
end
```
Reason: This avoids repeated Lua->engine method calls on the hot path by memoizing each player's SteamID once and reusing it until the player entity is gone.


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

-- Slower: repeated string reallocation/copying
local slow = ""
for i = 1, #pieces do
    slow = slow .. pieces[i]
end

-- Faster: collect pieces, then join once
local fastParts = {}
for i = 1, #pieces do
    fastParts[i] = pieces[i]
end
local fast = table.concat(fastParts, "")
```
Reason: `table.concat` is faster because it builds the final string in one pass instead of creating and copying a new string on every `..` iteration.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the extra Lua-side work inside `draw.RoundedBox(0, ...)` and is the cheaper direct path for plain, non-rounded rectangles.


```lua
local font = "BenchFont"
local text = "FPS: 144"
local x, y = 32, 32
local r, g, b, a = 255, 255, 255, 255

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(r, g, b, a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the leanest common path for single-line text; `draw.DrawText` adds wrapping/alignment work, `draw.SimpleTextOutlined` draws multiple passes for the outline, and both wrapper APIs add avoidable per-frame overhead.


```lua
local len = #tbl
```
Reason: `#` is the idiomatic and fastest way to get the length of a contiguous sequential array-like table in Garry's Mod Lua.


```lua
-- Faster in general when you can replace the table reference.
t = {}
```
Reason: `t = {}` is usually faster because it avoids clearing every existing element one by one; it just points `t` at a new table and leaves the old one for garbage collection, while `table.Empty(t)` does O(n) work.


```lua
local allowed = {
    apple = true,
    banana = true,
    orange = true,
}

if allowed[value] then
    print("value exists")
end
```
Reason: `table.HasValue` scans the whole list linearly, while a set-style table lookup by key is constant-time on average and is much faster for repeated membership checks.


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

-- Slower
local t2 = {}
t2.x = 1
t2.y = 2
t2.z = 3
```
Reason: Putting known fields directly in the table constructor is faster because it creates and fills the table in one step, avoiding separate field assignment operations.


```lua
local value = list[math.random(#list)]
```
Reason: For a sequential array, direct indexing with a random integer avoids `table.Random`'s extra generic-table work and is faster.


```lua
local x2 = x * x
```
Reason: `x * x` is the direct arithmetic operation and avoids the extra overhead of generic power helpers like `math.pow` or `x ^ 2` in a hot loop.


```lua
for _, ply in player.Iterator() do
    -- use ply
end
```
Reason: `player.Iterator()` iterates connected players directly without creating the temporary table that `player.GetAll()` returns.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` walks the entity list directly, so it avoids building a full table of all map entities first.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Think callback
end)
```
Reason: `hook.Add` registers a function on Garry's Mod's `Think` hook, and `MyAddon.Think` is the unique identifier for that callback.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that the reference exists and the entity has not been removed, so calling methods on it is safe.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` registers the callback that runs when the `MyAddon.Sync` net message arrives.


```lua
-- Slow in a hot path: allocates a new Angle every call.
-- local ang = Angle()

local scratchAng = Angle()

local function HotPath()
    scratchAng.p = 0
    scratchAng.y = 0
    scratchAng.r = 0

    -- use scratchAng immediately here
    -- do not keep or return it if later code needs a unique Angle
end
```
Reason: Reusing one preallocated `Angle` and resetting its fields avoids repeated allocation and garbage collection, which is faster than calling `Angle()` every time.


```lua
local MYADDON_COLOR = Color(255, 200, 0)

local color = MYADDON_COLOR
```
Reason: A local variable is fastest to read in Garry's Mod Lua; nested table access like `myaddon.config.color` adds one or more table lookups, and globals are also slower than locals.


```lua
-- Preferred over ply:GetNWString("job")
local jobName = team.GetName(ply:Team())

-- Not preferred
local oldJobName = ply:GetNWString("job")
```
Reason: DarkRP jobs are teams, so `team.GetName(ply:Team())` uses the canonical server-side source instead of a fragile raw networked string.


```lua
if pos1:DistToSqr(pos2) <= (maxDistance * maxDistance) then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root that `Distance` does, so it is the preferred fast threshold check in Garry's Mod Lua.


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
end
```
Reason: `ents.Iterator()` is the Garry's Mod wiki-recommended way to visit every entity when available because it avoids creating the full table from `ents.GetAll()` and is more efficient.


```lua
local pos = ply:GetPos()
local radius = 512
local extents = Vector(radius, radius, radius)

for _, ent in ipairs(ents.FindInBox(pos - extents, pos + extents)) do
    if ent ~= ply then
        -- handle nearby entity
    end
end
```
Reason: `ents.FindInBox` is a common fast pick for cheap nearby-entity queries because the engine only does an axis-aligned bounds test, which is typically cheaper than sphere distance checks and avoids relying on PVS visibility semantics.


```lua
local player_GetAll = player.GetAll

local function FindPlayersNear(pos, radius, out)
    out = out or {}

    local radiusSqr = radius * radius
    local count = 0

    for _, ply in ipairs(player_GetAll()) do
        if pos:DistToSqr(ply:GetPos()) <= radiusSqr then
            count = count + 1
            out[count] = ply
        end
    end

    for i = count + 1, #out do
        out[i] = nil
    end

    return out
end
```
Reason: This only scans players and uses squared distance checks, so it avoids `ents.FindInSphere` walking all entities and avoids the extra player-filter pass.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` is generally faster in Garry's Mod Lua because the VM handles the counter, limit, and step in a specialized loop path with less per-iteration overhead than a manual `while` counter update.


```lua
-- Faster: one hook dispatch, then loop inside the hook listener.
local players = player.GetAll()
hook.Run("MyTickAllPlayers", players)

hook.Add("MyTickAllPlayers", "MyCustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- per-player logic here
    end
end)

-- Slower: repeated hook dispatch per player.
local players = player.GetAll()
for i = 1, #players do
    hook.Run("MyTickPlayer", players[i])
end
```
Reason: Calling `hook.Run` once avoids repeated hook dispatch, lookup, and vararg/call overhead each tick; the per-player loop is cheaper when done inside one hook handler.


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

    local health = lp:Health()

    draw.SimpleText(health, "Trebuchet24", 32, 32, color_white)
    draw.RoundedBox(0, 32, 64, health * 2, 20, Color(200, 60, 60))
    draw.SimpleText(health .. "%", "Trebuchet18", 32, 90, Color(255, 200, 200))
end)
```
Reason: It does `LocalPlayer()` and `:Health()` once per frame, then reuses the cached value across all three draw calls instead of repeating the lookup 3 times.


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

function PANEL:Paint(w, h)
    for i = 1, 1000 do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(i, 0, 1, h)
    end
end
```
Reason: `Color()` allocates a new table each iteration; caching one immutable color and reusing it avoids per-frame allocations and GC pressure.


```lua
local sin = math.sin

for i = 1, 100000 do
    local y = sin(i)
    -- hot loop work
end
```
Reason: Caching `math.sin` in a local avoids repeated table lookups on `math` inside the hot loop.


```lua
local localPlayer = NULL

local function GetLocalPlayerCached()
    if not IsValid(localPlayer) then
        localPlayer = LocalPlayer()
    end

    return localPlayer
end

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

    local pos = ply:GetPos()
    local vel = ply:GetVelocity()
end)
```
Reason: Caching the entity in a local upvalue avoids repeated global `LocalPlayer()` lookups, while the validity check refreshes it safely when the client player entity is not ready or gets recreated.


```lua
local FACE_DOT = -0.85 -- lower means closer to directly facing each other (-1 = exact opposite)

local function AreRoughlyLookingAtEachOther(plyA, plyB)
    return plyA:GetAimVector():Dot(plyB:GetAimVector()) <= FACE_DOT
end
```
Reason: `GetAimVector()` gives normalized direction vectors, so a dot-product threshold is much cheaper than computing an angle with `math.acos`, and “looking at each other” means the two aim vectors are roughly opposite (dot near `-1`).


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally a bit faster for a helper you control, especially if `SomeHelper` is local, because `ply:SomeHelper()` implies a field lookup plus implicit `self` passing.


```lua
local MsgN = MsgN

MsgN("[debug] hot path reached")
```
Reason: `MsgN` is a lighter console write than `print`, and caching it in a local avoids repeated global lookups in a hot path.


```lua
local sum = 0
for i = 1, #numbers do
    sum = sum + numbers[i]
end
```
Reason: `numeric for` over `1 .. #numbers` is typically fastest for a large dense array in Garry's Mod Lua because it avoids the iterator overhead of `pairs` and `ipairs` and uses direct indexed access.


```lua
local function filterMap(list, keep, project)
    local out = {}
    local n = 0

    for i = 1, #list do
        local v = list[i]
        if keep(v) then
            n = n + 1
            out[n] = project(v)
        end
    end

    return out
end

-- Equivalent to a fn-style filter -> map pipeline, but faster in GMod hot paths.
local richCitizenNames = filterMap(player.GetAll(),
    function(ply)
        return IsValid(ply)
            and ply:Alive()
            and ply:Team() == TEAM_CITIZEN
            and (ply:getDarkRPVar("money") or 0) >= 10000
    end,
    function(ply)
        return ply:Nick()
    end
)
```
Reason: One indexed loop does the filter and map in a single pass, avoiding fn’s extra function-call overhead and intermediate tables.


```lua
local cachedPlayers = player.GetAll()
local cachedIndex = {}

for i = 1, #cachedPlayers do
    cachedIndex[cachedPlayers[i]] = i
end

local function addCachedPlayer(ply)
    if cachedIndex[ply] then return end

    local i = #cachedPlayers + 1
    cachedPlayers[i] = ply
    cachedIndex[ply] = i
end

local function removeCachedPlayer(ply)
    local i = cachedIndex[ply]
    if not i then return end

    local last = #cachedPlayers
    local swapped = cachedPlayers[last]

    cachedPlayers[i] = swapped
    cachedPlayers[last] = nil
    cachedIndex[ply] = nil

    if swapped ~= ply then
        cachedIndex[swapped] = i
    end
end

hook.Add("PlayerInitialSpawn", "MyPlayerCacheAdd", addCachedPlayer)
hook.Add("PlayerDisconnected", "MyPlayerCacheRemove", removeCachedPlayer)

hook.Add("Tick", "MyHotTick", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]

        -- hot per-player work here
        -- if IsValid(ply) then ... end
    end
end)
```
Reason: This removes the `player.GetAll()` table rebuild from every tick and only updates the cached array on join/leave, cutting repeated allocation and per-tick traversal overhead on the hot path.


```lua
local someFieldByPlayer = {}

local function SetSomeField(ply, value)
    someFieldByPlayer[ply] = value
end

local function GetSomeField(ply)
    return someFieldByPlayer[ply]
end

hook.Add("PlayerDisconnected", "ClearSomeFieldCache", function(ply)
    someFieldByPlayer[ply] = nil
end)

-- hot read path
local value = someFieldByPlayer[ply]
if value then
    -- use value
end
```
Reason: A local side table keyed by `ply` is a plain Lua table lookup; `ply.someField` on Garry's Mod player/entity objects goes through a slower userdata/entity field access path.


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

for i = 1, #values do
    local v = values[i]
    -- use v
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps in Garry's Mod Lua because they use the table's array part and avoid per-entry hash lookups.


```lua
surface.SetDrawColor(255, 120, 40, 255)
```
Reason: Passing raw numbers is faster on a hot draw path because it avoids Color table/object handling and the extra type/field work that comes with the Color overload.


```lua
local steamId = SQLStr(ply:SteamID())
local row = sql.QueryRow("SELECT money FROM players WHERE steamid = " .. steamId)
```
Reason: Local SQLite via Garry's Mod `sql` is typically lower latency on a single server because it avoids network round trips and remote database overhead.


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

local function GetCachedSteamID(ply)
    local sid = steamIdCache[ply]
    if sid ~= nil then
        return sid
    end

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

-- Hot path
local function DoWork(players)
    for i = 1, #players do
        local ply = players[i]
        local sid = GetCachedSteamID(ply)

        -- use sid multiple times here without calling ply:SteamID() again
        SomeLookup(sid)
        SomeOtherLookup(sid)
    end
end
```
Reason: It turns repeated method calls into one lookup per player, and the weak-key cache avoids keeping disconnected player objects alive.


```lua
local parts = {}

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

local big = table.concat(parts)
```
Reason: `table.concat` builds the final string in one pass, avoiding the repeated reallocations and copying caused by `big = big .. piece` in a large loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` adds wrapper overhead, while `surface.DrawRect` is the direct plain-rectangle draw path for non-rounded boxes.


```lua
local FONT = "Trebuchet24"
local TEXT = "FPS: 144"
local X, Y = 24, 24
local R, G, B, A = 255, 255, 255, 255

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(FONT)
    surface.SetTextColor(R, G, B, A)
    surface.SetTextPos(X, Y)
    surface.DrawText(TEXT)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the lean single-line path; `draw.DrawText` adds wrapper/alignment/multiline work, and `draw.SimpleTextOutlined` is slower still because it draws the text multiple times for the outline.


```lua
local len = #myArray
```
Reason: `#` is the preferred way to get the length of a sequential array-like table; it is simpler and avoids the extra work of counting all keys.


```lua
t = {}
```
Reason: `t = {}` is generally faster for large sequential tables because it replaces the reference in O(1) instead of walking and niling every element like `table.Empty(t)`; use `table.Empty(t)` only when other code must keep the same table object.


```lua
local allowed = {
    foo = true,
    bar = true,
    baz = true,
}

if allowed[value] then
    -- value exists in the set
end
```
Reason: `table.HasValue` scans a list linearly, while keyed lookup in a set-style table is constant-time on average.


```lua
-- Faster
local t = {
    x = 1,
    y = 2,
    z = 3,
}

-- Slower
local t2 = {}
t2.x = 1
t2.y = 2
t2.z = 3
```
Reason: For a small table with known fields, the table constructor is faster because Lua can allocate and fill the table in one construction path instead of creating `{}` first and then doing separate field assignments.


```lua
local t = { "a", "b", "c", "d" }
local value = t[math.random(#t)]
```
Reason: For a sequential array, direct index lookup with `math.random(#t)` avoids `table.Random`'s extra generic-table handling and is faster.


```lua
local y = x * x
```
Reason: `x * x` avoids exponentiation overhead and is the usual fastest form in tight Lua loops.


```lua
for _, ply in player.Iterator() do
    -- use ply here
end
```
Reason: `player.Iterator()` visits connected players directly without creating the temporary table that `player.GetAll()` returns.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` walks entities lazily, so it avoids allocating a full table of every entity like `ents.GetAll()` would.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- per-frame logic here
end)
```
Reason: `hook.Add` registers a callback on Garry's Mod's `Think` hook, and `MyAddon.Think` is the unique identifier for that registration.


```lua
if not IsValid(ent) then return end
ent:SomeMethod()
```
Reason: `IsValid(ent)` filters out `nil`, `NULL`, and deleted/invalid entities before you call methods on them.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here.
end)
```
Reason: `net.Receive` is the Garry's Mod API for registering a callback that runs when the `MyAddon.Sync` net message arrives.


```lua
local scratchAng = Angle(0, 0, 0)

local function getZeroedAngle()
    scratchAng:SetUnpacked(0, 0, 0)
    return scratchAng
end

-- slower in a hot path:
-- local ang = Angle(0, 0, 0)
```
Reason: Reusing one `Angle` and resetting its components avoids repeated allocation and constructor overhead, which is faster in hot code.


```lua
local addonColor = myaddon.config.color
local color = addonColor
```
Reason: A local is fastest because it avoids repeated table/environment lookups; `myaddon.config.color` does multiple indexed lookups on every read.


```lua
-- Avoid: ply:GetNWString("job")
local jobName = ply:getDarkRPVar("job")
```
Reason: `getDarkRPVar("job")` is DarkRP's supported accessor for the job value, so it avoids relying on a hardcoded raw NWString key.


```lua
local maxDist = 200
if pos1:DistToSqr(pos2) <= (maxDist * maxDist) then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root from `Distance`, so it is faster for threshold-only comparisons.


```lua
if ents.Iterator then
    for _, ent in ents.Iterator() do
        -- visit every entity here
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- fallback for environments without the iterator
    end
end
```
Reason: `ents.Iterator()` avoids building a full entity table and is the efficient wiki-recommended choice for simple iteration, while `ents.GetAll()` is a safe fallback when that iterator is unavailable.


```lua
local radius = 512
local nearby = ents.FindInSphere(ply:GetPos(), radius)
```
Reason: `ents.FindInSphere` is a common fast built-in for nearby-entity queries, matches the "near a player" shape directly, and avoids using `FindInPVS` as the default choice.


```lua
local function FindPlayersNear(pos, radius, out)
    out = out or {}

    local count = 0
    local radiusSqr = radius * radius
    local players = player.GetAll()

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

    for i = count + 1, #out do
        out[i] = nil
    end

    return out
end

-- usage
local nearbyPlayers = FindPlayersNear(targetPos, 512)
```
Reason: It scans only players and uses squared distance, so it avoids `ents.FindInSphere` doing a broader entity query plus per-entity player filtering.


```lua
for i = 1, n do
    -- hot loop body
end
```
Reason: `for` is generally faster for 1..n counting in Garry's Mod Lua because numeric `for` loops use a specialized VM loop path with less per-iteration overhead than a manual `while` counter update/check.


```lua
-- Faster: dispatch one hook per tick with the full player list.
hook.Add("Tick", "NotifyAllPlayersFast", function()
    hook.Run("MyPlayersTick", player.GetAll())
end)

hook.Add("MyPlayersTick", "CustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- per-player logic here
    end
end)

-- Slower: dispatching the hook once per player every tick.
hook.Add("Tick", "NotifyAllPlayersSlow", function()
    local players = player.GetAll()
    for i = 1, #players do
        hook.Run("MyPlayerTick", players[i])
    end
end)
```
Reason: Calling `hook.Run` once avoids paying hook dispatch, lookup, and function-call overhead for every player each tick.


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

    draw.SimpleText(hp, "DermaLarge", 32, 32, color_white)
    draw.RoundedBox(4, 32, 72, hp * 2, 20, Color(200, 60, 60))
    draw.SimpleText("HP: " .. hp, "DermaDefault", 32, 98, color_white)
end)
```
Reason: It caches `LocalPlayer():Health()` once per frame, avoiding three repeated Lua-to-engine calls inside `HUDPaint`.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(WHITE)

    for i = 1, self.BarCount do
        surface.DrawRect(0, (i - 1) * 2, w, 1)
    end
end
```
Reason: `Color(255,255,255)` allocates work every iteration; caching the `Color` once and reusing it removes repeated allocation and setup from the hot paint path.


```lua
local sin = math.sin

for i = 1, 1000000 do
    local y = sin(i)
    -- hot loop work
end
```
Reason: Caching `math.sin` in a local avoids repeated table/global lookup inside the hot loop, which is slightly faster in Lua.


```lua
local _LocalPlayer = LocalPlayer
local lp

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

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

    local hp = ply:Health()
    local armor = ply:Armor()
    local pos = ply:GetPos()

    -- use ply repeatedly here instead of calling LocalPlayer() each time
end)
```
Reason: It caches both the global function lookup and the player entity, so repeated code uses a local upvalue instead of redoing a global lookup and function call every time.


```lua
local FACE_EACH_OTHER_DOT = -0.85 -- ~= 148 degrees apart; closer to -1 means more directly facing each other

local function AreRoughlyLookingAtEachOther(plyA, plyB)
    return plyA:GetAimVector():Dot(plyB:GetAimVector()) <= FACE_EACH_OTHER_DOT
end
```
Reason: `GetAimVector()` returns normalized vectors, so a single dot-product compare is enough; it avoids `math.acos`, extra angle conversion, and is the cheap way to test whether their aim directions are roughly opposite.


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

SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster for helpers you control because a direct local function call avoids the table/metatable method lookup behind `ply:SomeHelper()`.


```lua
MsgN("[debug] hot path hit")
```
Reason: `MsgN` is typically faster than `print` in Garry's Mod because it writes directly to the console with less argument-formatting overhead and already includes the newline.


```lua
for i = 1, #nums do
    local v = nums[i]
    -- use v
end
```
Reason: `numeric for` is typically fastest for a large dense array because it avoids the iterator overhead of `ipairs` and the hash-style traversal of `pairs`, while doing direct indexed access.


```lua
local IsValid = IsValid

-- Same work as a small filter/map pipeline:
-- keep alive players with enough money, then collect their names.
local function getRichAlivePlayerNames(players, minMoney)
    local out = {}
    local n = 0

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:Alive() then
            local money = ply:getDarkRPVar("money") or 0
            if money >= minMoney then
                n = n + 1
                out[n] = ply:Nick()
            end
        end
    end

    return out
end

local names = getRichAlivePlayerNames(player.GetAll(), 10000)
```
Reason: one tight numeric loop fuses filter and map into a single pass, avoids fn combinator closure/call overhead, and avoids intermediate tables.


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

hook.Add("PlayerInitialSpawn", "MyAddon_PlayerCacheAdd", function(ply)
    cachedPlayers[#cachedPlayers + 1] = ply
end)

hook.Add("PlayerDisconnected", "MyAddon_PlayerCacheRemove", function(ply)
    for i = 1, #cachedPlayers do
        if cachedPlayers[i] == ply then
            cachedPlayers[i] = cachedPlayers[#cachedPlayers]
            cachedPlayers[#cachedPlayers] = nil
            break
        end
    end
end)

hook.Add("Tick", "MyAddon_FastPlayerLoop", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- per-player tick work here
    end
end)
```
Reason: This removes the per-tick `player.GetAll()` allocation and traversal, so the hot path only iterates a stable cached array and updates it when players join or leave.


```lua
local tempByPly = {}

local function SetTempValue(ply, value)
    tempByPly[ply] = value
end

local function GetTempValue(ply)
    return tempByPly[ply]
end

hook.Add("PlayerDisconnected", "ClearTempValue", function(ply)
    tempByPly[ply] = nil
end)
```
Reason: A plain Lua side table keyed by `ply` avoids the player userdata/metatable field lookup path of `ply.someField`, so repeated reads are typically faster.


```lua
local values = {
    "crowbar",
    "pistol",
    "smg1",
    "shotgun",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays iterate faster because Lua stores them in the table's array part, so a numeric `for` loop avoids the hash lookup and `pairs` overhead of string-keyed maps.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing raw numbers avoids `Color` table construction and field lookups, so it is the lower-overhead call style in a hot draw path.


```lua
local coins = sql.QueryValue("SELECT coins FROM player_data WHERE steamid64 = " .. sql.SQLStr(ply:SteamID64()))
```
Reason: Local SQLite via Garry's Mod's `sql` library is typically lower latency on a single server because it avoids remote network round trips and query transport overhead.


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

local function SteamIDCached(ply)
    local sid = steamIDCache[ply]
    if sid ~= nil then
        return sid
    end

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

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

-- hot path
for i = 1, #players do
    local ply = players[i]
    local sid = SteamIDCached(ply)

    if sid == "STEAM_0:1:12345" then
        -- fast repeated use of sid here
    end
end
```
Reason: `SteamID()` is stable per connected player, so caching replaces repeated method calls on the hot path with a single call plus cheap Lua table reads; weak keys keep the cache from growing forever.


```lua
-- Slow:
-- local s = ""
-- for i = 1, 10000 do
--     s = s .. getPiece(i)
-- end

-- Fast:
local parts = {}
for i = 1, 10000 do
    parts[i] = getPiece(i)
end

local s = table.concat(parts)
```
Reason: Repeated `..` builds a new string on every loop and recopies old content, while `table.concat` joins all pieces once with far less allocation and copying.


```lua
surface.SetDrawColor(col.r, col.g, col.b, col.a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is the direct non-rounded rectangle path, so it avoids `draw.RoundedBox(0, ...)` wrapper overhead and extra corner logic.


```lua
local text = "Hello"
local font = "Trebuchet24"
local col = Color(255, 255, 255)
local x, y = 32, 32

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(col)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the lower-overhead path for single-line text; `draw.DrawText` does extra wrapper work for formatting/alignment and `draw.SimpleTextOutlined` is slower because it draws the text multiple times for the outline.


```lua
local len = #myTable
```
Reason: For a contiguous 1-based array-like table, `#` is the idiomatic and preferred way to get its length; `table.Count` is for general keyed tables and has to iterate.


```lua
-- Faster when you do not need to preserve existing references.
t = {}
```
Reason: `t = {}` is generally faster for large sequential tables because it only rebinds the variable, while `table.Empty(t)` must iterate the existing table and clear entries in place; use `table.Empty(t)` only if the same table reference must stay valid.


```lua
local allowedWeapons = {
    pistol = true,
    shotgun = true,
    crowbar = true,
}

-- Faster than table.HasValue({"pistol", "shotgun", "crowbar"}, weaponClass)
if allowedWeapons[weaponClass] then
    -- value exists
end
```
Reason: `table.HasValue` scans the whole list linearly, while a set-style table does a direct key lookup with average O(1) membership checks.


```lua
-- Faster for a small table with known fields:
local t = {
    a = 1,
    b = 2,
    c = 3,
}

-- Slower:
-- local t = {}
-- t.a = 1
-- t.b = 2
-- t.c = 3
```
Reason: Putting known fields in the table constructor is faster because Lua can allocate and initialize the table in one step instead of doing separate field stores after creating `{}`.


```lua
local function randomSequential(t)
    local n = #t
    if n == 0 then return nil end
    return t[math.random(n)]
end
```
Reason: For a sequential table, direct array indexing with `t[math.random(#t)]` is O(1) and avoids the generic key handling overhead in `table.Random`.


```lua
local x2 = x * x
```
Reason: `x * x` is the preferred fast form in a tight loop because plain multiplication is cheaper than exponentiation like `x ^ 2`.


```lua
for _, ply in player.Iterator() do
    -- use ply here
end
```
Reason: `player.Iterator()` visits connected players directly without creating the intermediate table that `player.GetAll()` returns.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- visit ent here
end
```
Reason: `ents.FindByClass` already returns only entities of that class, so this loops them directly without building a full entity list first.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: This registers a function on Garry's Mod's `Think` hook under the identifier `MyAddon.Think`.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: `IsValid` is the standard Garry's Mod check for an entity reference that still exists and can be used safely.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming message here
end)
```
Reason: `net.Receive` registers the client or server callback for an incoming Garry's Mod net message by name.


```lua
-- Reuse the built-in zero Angle instead of allocating a new one each call.
local a = angle_zero

-- Example hot path use:
-- pos = pos + forward * 10
-- ang = angle_zero
```
Reason: `angle_zero` is a shared prebuilt zero `Angle`, so it avoids repeated `Angle()` allocations in a hot path.


```lua
local addon_color = Color(255, 255, 255)
local c = addon_color
```
Reason: a flat local is faster to read than repeated nested table lookups because it avoids multiple table index operations and global access is slower still.


```lua
local jobName = ply:getDarkRPVar("job")
-- fallback if needed:
-- local jobName = team.GetName(ply:Team())
```
Reason: `getDarkRPVar("job")` reads DarkRP's job data directly; `GetNWString("job")` is the lower-level networked-value path and is not the preferred DarkRP API.


```lua
if vec1:DistToSqr(vec2) <= threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root cost of `Distance()` and is the preferred way to do a threshold comparison.


```lua
for _, ent in ents.Iterator() do
    -- visit every entity here
end
```
Reason: `ents.Iterator()` is the efficient entity iterator, so it avoids building a full table like `ents.GetAll()` when iterating all entities.


```lua
local ply = self:GetOwner()
if not IsValid(ply) then return end

local origin = ply:GetPos()
local radiusSqr = 400 * 400
local nearby = {}

for _, ent in ipairs(ents.FindInSphere(origin, 400)) do
    if IsValid(ent) and ent ~= ply and ent:GetPos():DistToSqr(origin) <= radiusSqr then
        nearby[#nearby + 1] = ent
    end
end
```
Reason: `ents.FindInSphere` is one of the faster built-in broadphase queries for nearby entities, and the squared-distance filter keeps the final check cheap without using `FindInPVS`.


```lua
local radiusSqr = radius * radius
local out = {}
local n = 0

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

return out
```
Reason: `player.GetAll()` only iterates players, so it avoids `ents.FindInSphere` building a mixed entity list and then discarding non-player entities.


```lua
for i = 1, n do
    -- tight loop body
end
```
Reason: In Garry's Mod Lua, the numeric `for` loop is generally faster than a `while` loop for simple counted iteration because the iteration machinery is optimized by the Lua VM.


```lua
-- Faster: one hook call per tick, pass the whole player list.
hook.Run("MyTickHook", player.GetAll())

-- Slower: one hook call per player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTickHook", ply)
end
```
Reason: `hook.Run` has nontrivial dispatch overhead, so calling it once per tick avoids repeating that cost for every player.


```lua
local hp = LocalPlayer():Health()

-- use hp for all three draw calls
```
Reason: Caches the player health once per frame instead of calling `LocalPlayer():Health()` three times.


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

for i = 1, #items do
    surface.SetDrawColor(WHITE)
    -- paint item
end
```
Reason: Hoist the invariant `Color(255,255,255)` allocation out of the loop so the loop reuses one cached color instead of creating a new table every iteration.


```lua
local sin = math.sin

for i = 1, n do
    local y = sin(x[i])
    -- use y
end
```
Reason: Caching `math.sin` in a local avoids repeated table lookups inside the hot loop.


```lua
local LocalPlayer = LocalPlayer
local cachedLP = nil
local cachedFrame = -1

local function GetLocalPlayerFast()
    local frame = FrameNumber()
    if frame ~= cachedFrame then
        cachedFrame = frame
        cachedLP = LocalPlayer()
    end

    return cachedLP
end

-- use GetLocalPlayerFast() instead of calling LocalPlayer() repeatedly
```
Reason: `LocalPlayer()` is cached once per frame, so repeated calls in the same frame reuse the same player entity instead of doing the lookup every time.


```lua
-- Returns true when each player's aim is generally pointing toward the other.
-- Tune the threshold: 0.7 ~= within about 45 degrees, 0.5 ~= about 60 degrees.
local function PlayersRoughlyLookingAtEachOther(plyA, plyB, threshold)
    threshold = threshold or 0.7

    local posA = plyA:EyePos()
    local posB = plyB:EyePos()

    local aimA = plyA:EyeAngles():Forward()
    local aimB = plyB:EyeAngles():Forward()

    local toB = (posB - posA):GetNormalized()
    local toA = -toB

    -- Dot product is cheap: 1 = same direction, 0 = perpendicular, -1 = opposite.
    return aimA:Dot(toB) >= threshold and aimB:Dot(toA) >= threshold
end
```
Reason: Dot products compare direction similarity directly, so this avoids expensive angle math like `math.acos` while staying fast and easy to tune.


```lua
SomeHelper(ply)
```
Reason: For a helper you control, the plain function call is generally a bit faster and easier to optimize than a method-call syntax, because `ply:SomeHelper()` adds a `self` lookup and colon-call sugar that are unnecessary when the helper is not an object method.


```lua
MsgN("debug: value=" .. tostring(value))
```
Reason: `MsgN` writes straight to the console path without `print`'s extra formatting and vararg overhead, so it is the cheaper hot-path choice.


```lua
-- Fastest typical choice for a dense array-like table of numbers in Garry's Mod Lua
for i = 1, #t do
    local v = t[i]
    -- use i and v
end
```
Reason: A numeric `for` avoids iterator function overhead and hash traversal, so it is typically faster than `pairs` or `ipairs` on a large sequential array.


```lua
-- Fused filter/map pipeline: one pass, one output table, no combinator chain.
local function transform_list(input, predicate, mapper)
    local out = {}
    local n = 0

    for i = 1, #input do
        local v = input[i]
        if predicate(v, i) then
            n = n + 1
            out[n] = mapper(v, i)
        end
    end

    return out
end

-- Example usage:
-- keep players with a job, map to their DarkRP name
local result = transform_list(players.GetAll(), function(ply)
    return IsValid(ply) and ply:Team() ~= TEAM_UNASSIGNED
end, function(ply)
    return ply:Nick()
end)
```
Reason: This is faster because it does the filter and map in a single numeric `for` loop with no intermediate closures or chained combinator calls, so it cuts per-item call overhead and table churn.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "RefreshCachedPlayersOnJoin", RefreshPlayers)
hook.Add("PlayerDisconnected", "RefreshCachedPlayersOnLeave", RefreshPlayers)

hook.Add("Think", "UseCachedPlayersInThink", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- per-player work here
        end
    end
end)
```
Reason: `player.GetAll()` is moved out of the hot Tick/Think path and only recomputed on join/leave, so the hook iterates a cached table each frame instead of rebuilding it every tick.


Answer must contain exactly one fenced code block followed by a reason.

local TempPlayerData = setmetatable({}, { __mode = "k" })

-- write
TempPlayerData[ply] = value

-- read
local value = TempPlayerData[ply]


```lua
-- Faster for iteration: sequential number-indexed array
local values = { "a", "b", "c" }
for i = 1, #values do
    local v = values[i]
end

-- Slower for iteration: string-keyed map
local map = { a = 1, b = 2, c = 3 }
for k, v in pairs(map) do
end
```
Reason: Sequential arrays are typically faster to iterate in Garry's Mod Lua because the numeric array part is optimized for ordered traversal, while string-keyed maps use hash lookups.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing separate `r, g, b, a` numbers avoids the extra `Color` object path and is the faster choice for a hot draw loop.


```lua
sql.Query("SELECT * FROM players WHERE steamid = '" .. sql.SQLStr(steamID) .. "'")
```
Reason: For a single Garry's Mod server with no sync requirement, local SQLite is typically lower latency than remote MySQL because it avoids network round trips and external connection overhead.


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

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

-- hot path usage
for i = 1, #players do
    local ply = players[i]
    local steamid = GetSteamIDCached(ply)
    -- use steamid here
end
```
Reason: Cache the per-player SteamID once and reuse it, avoiding repeated `ply:SteamID()` calls and letting weak keys drop dead players automatically.


```lua
-- Slow: repeated .. builds a new string every time.
local out = ""
for i = 1, 10000 do
    out = out .. "piece" .. i
end

-- Faster: collect parts, join once.
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece"
    parts[#parts + 1] = i
end
local out2 = table.concat(parts)
```
Reason: `table.concat` joins once at the end, while repeated `..` reallocates and copies the whole string many times.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips the rounded-box path and is the direct filled-rectangle primitive for plain rectangles.


```lua
surface.SetFont("Trebuchet24")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the leanest per-frame path here; it avoids the extra wrapper work in `draw.DrawText`, and `SimpleTextOutlined` adds more overhead for outlining and extra passes.


```lua
local n = #tbl
-- or, for a sequential array-like table, use the length operator above
```
Reason: In Garry's Mod Lua, the preferred way to get the length of a sequential array-like table is the `#` length operator.


```lua
-- Fastest when you do not need to keep the same table object:
t = {}
```
Reason: `t = {}` is usually faster because it just creates a new empty table, while `table.Empty(t)` walks the existing table and clears it in place; use `table.Empty(t)` only when other references must see the table emptied.


```lua
-- Fast membership check: use a keyed set table, not table.HasValue on an array
local allowed = {
  ["weapon_pistol"] = true,
  ["weapon_smg1"] = true,
  ["weapon_shotgun"] = true,
}

if allowed[value] then
  -- value exists in the set
end

-- For comparison, table.HasValue scans the whole list linearly:
-- if table.HasValue(list, value) then ... end
```
Reason: keyed lookup is O(1) average, while table.HasValue on a list does a linear scan.


```lua
local t = { a = 1, b = 2, c = 3 }
```
Reason: The table constructor is faster for known fields because it creates the table and fills the fields in one step, while assigning after `{}` does extra writes.


```lua
local function FastRandomSequential(t)
    return t[math.random(#t)]
end
```
Reason: `table.Random` works on generic tables and pays extra overhead; for a sequential array, `#t` plus direct indexing is faster and simpler.


```lua
local y = x * x
```
Reason: `x * x` is the fastest clear form in tight Lua loops, with no function call overhead or extra arithmetic.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- your code here
end
```
Reason: `player.GetAll()` returns the currently connected players, and `ipairs` iterates that array-style list in order.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, so you can filter `prop_physics` without allocating a full `ents.GetAll()` table.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a Think callback under the `MyAddon.Think` identifier.


```lua
if IsValid(ent) then
    -- safe to call entity methods here
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check for a live entity reference before using it.


```lua
net.Receive("MyAddon.Sync", function(len)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` registers the callback that runs when the incoming `MyAddon.Sync` message arrives.


```lua
local ZERO_ANGLE = angle_zero

-- hot path: reuse the shared zero Angle instead of allocating a new one
local ang = ZERO_ANGLE
```
Reason: `angle_zero` is already a zeroed Angle, so reusing it avoids constructing a new `Angle()` object every time.


```lua
local myaddon_color = Color(255, 128, 0)

print(myaddon_color.r)
```
Reason: a local upvalue/variable is faster to read than repeatedly indexing nested tables because it avoids extra table lookups.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred DarkRP accessor
```
Reason: `ply:getDarkRPVar("job")` is the DarkRP API for the job label; `ply:GetNWString("job")` reads the underlying networked value directly.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root used by `DistTo`, so it is the preferred way to do a distance threshold check.


```lua
for ent in ents.Iterator() do
    -- process each entity here
end
```
Reason: `ents.Iterator()` is the efficient entity iterator, so it avoids building a full table like `ents.GetAll()` when you only need to visit each entity once.


```lua
local pos = ply:GetPos()
local radius = 512
local mins = pos - Vector(radius, radius, radius)
local maxs = pos + Vector(radius, radius, radius)

for _, ent in ipairs(ents.FindInBox(mins, maxs)) do
    if IsValid(ent) and ent ~= ply then
        -- nearby entity
    end
end
```
Reason: `ents.FindInBox` is a fast built-in broadphase query in common GMod benchmarks, and it gives a cheap near-player candidate set without relying on `FindInPVS`.


```lua
local function PlayersInSphere(pos, radius)
    local radiusSqr = radius * radius
    local found = {}
    local n = 0

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

    return found, n
end
```
Reason: `player.GetAll()` iterates only players, and `DistToSqr` avoids the square root, so it is cheaper than scanning every entity with `ents.FindInSphere` and then filtering.


```lua
for i = 1, n do
    -- tight counting loop
end
```
Reason: In Garry's Mod Lua, the numeric `for` loop is generally faster than `while` for a simple 1-to-n counter because the VM handles the loop control more efficiently.


```lua
-- Faster: one dispatch, pass the whole player list to the hook.
local players = player.GetAll()
hook.Run("MyCustomTick", players)

-- Slower: one dispatch per player.
for i = 1, #players do
    hook.Run("MyCustomTick", players[i])
end
```
Reason: One `hook.Run` amortizes hook lookup and dispatch overhead across all players, while the per-player loop repeats that cost every tick.


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

    local health = lp:Health()

    draw.SimpleText("HP: " .. health, "Trebuchet24", 50, 50, color_white)
    draw.SimpleText("Health: " .. health .. "%", "Trebuchet24", 50, 70, color_white)
    draw.RoundedBox(4, 50, 90, math.Clamp(health, 0, 100) * 2, 16, color_red)
end)
```
Reason: Caches `LocalPlayer()` and `Health()` once per frame, so the three draw calls reuse the same value instead of repeating the lookup.


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

hook.Add("HUDPaint", "MyPaintLoop", function()
    surface.SetDrawColor(WHITE)
    -- draw loop here, reuse WHITE instead of allocating a new Color each iteration
end)
```
Reason: `Color(255, 255, 255)` allocates a new color table each time; hoisting one shared `WHITE` color avoids repeated allocations in the paint loop.


```lua
local sin = math.sin

for i = 1, n do
    local y = sin(x[i])
    -- use y
end
```
Reason: `math.sin` is a global table lookup; caching it in a local avoids repeating that lookup in a hot loop.


```lua
local lp = LocalPlayer()

hook.Add("Think", "CacheLocalPlayer", function()
    if not IsValid(lp) then
        lp = LocalPlayer()
    end
end)

-- use lp instead of calling LocalPlayer() every time
if IsValid(lp) then
    print(lp:Nick())
end
```
Reason: `LocalPlayer()` is a function call; caching the entity in a local and refreshing it only when needed avoids repeated lookup and call overhead.


```lua
local function RoughlyLookingAtEachOther(ply1, ply2, dotThreshold)
    dotThreshold = dotThreshold or 0.7 -- higher = tighter cone

    local eye1 = ply1:EyePos()
    local eye2 = ply2:EyePos()

    local dir12 = (eye2 - eye1):GetNormalized()
    local dir21 = -dir12

    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()

    return aim1:Dot(dir12) >= dotThreshold and aim2:Dot(dir21) >= dotThreshold
end
```
Reason: Dot products give a cheap cone check and avoid the expensive `math.acos` angle conversion.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster because `ply:SomeHelper()` is just sugar for a method lookup plus an extra implicit `self` argument.


```lua
MsgN("debug: ", tostring(value))
```
Reason: `MsgN` writes directly to the console with less formatting overhead than `print`, which makes it a better choice in a hot path.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: A numeric `for` over `1..#t` is typically fastest for a dense sequential array-like table in Garry's Mod Lua because it avoids iterator overhead and direct indexing is cheaper than `pairs` or `ipairs`.


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

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

    return out
end
```
Reason: One tight loop does filter and map in place, so it avoids the extra closures, iterator layers, and intermediate tables that DarkRP's fn combinators create.


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

hook.Add("PlayerInitialSpawn", "RefreshPlayerCacheOnJoin", function()
    cachedPlayers = player.GetAll()
end)

hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", function()
    cachedPlayers = player.GetAll()
end)

hook.Add("Think", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- work with ply
        end
    end
end)
```
Reason: Reuses one cached player list during Tick/Think and rebuilds it only on join/leave, avoiding `player.GetAll()` every frame.


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

-- write
tempByPlayer[ply] = value

-- read
local value = tempByPlayer[ply]
```
Reason: a local side table keeps reads to one plain table lookup and avoids entity-field access on the player object.


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

for i = 1, #values do
  local v = values[i]
  -- iterate sequentially
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because Lua can traverse them with a simple numeric loop and contiguous storage patterns, while string-keyed lookup adds hash overhead.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing raw `r, g, b, a` numbers avoids a `Color` object lookup/conversion in a hot draw path.


```lua
local rows = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid) .. ";")
```
Reason: For a single Garry's Mod server with no cross-server sync, local SQLite is typically lower latency because it avoids network round trips and remote connection overhead.


```lua
local steamid_cache = setmetatable({}, { __mode = "k" }) -- weak keys so disconnected players can fall out

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

-- hot path: call once, reuse the cached string
for _, ply in ipairs(player.GetAll()) do
    local sid = GetSteamIDFast(ply)
    if sid == "STEAM_0:1:12345" then
        -- ...
    end
    if sid == "STEAM_0:1:12345" then
        -- reuse sid again instead of ply:SteamID()
    end
end
```
Reason: Memoizing `ply:SteamID()` per player removes repeated method calls in the hot path, and a weak-key cache avoids holding disconnected players alive.


```lua
-- Slow: repeated .. creates many intermediate strings
local out = ""
for i = 1, 10000 do
    out = out .. "piece" .. i .. ","
end

-- Fast: collect parts, concatenate once
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece"
    parts[#parts + 1] = i
    parts[#parts + 1] = ","
end
local out_fast = table.concat(parts)
```
Reason: `table.concat` builds the final string in one pass, avoiding the repeated intermediate allocations and copies caused by `..` in a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` does extra rounded-box handling; `surface.DrawRect` is the direct non-rounded rectangle primitive and is slightly faster for lots of per-frame rectangles.


```lua
surface.CreateFont("HUDTextFast", {
    font = "Roboto",
    size = 24,
    weight = 500,
    antialias = true,
})

local text = "Hello, world"

hook.Add("HUDPaint", "DrawFastText", function()
    surface.SetFont("HUDTextFast")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the leanest path for a single-line string; it avoids the extra positioning, alignment, and outline work done by `draw.DrawText` and `draw.SimpleTextOutlined`.


```lua
local len = #tbl
```
Reason: `#tbl` is the standard Lua length operator for sequential array-like tables; `table.Count` is for counting all keys in a table, not just array length.


```lua
t = {}
```
Reason: Rebinding to a new table is generally faster than clearing a large existing table with `table.Empty(t)`, because `table.Empty` must walk and remove the old entries.


```lua
-- Build once
local allowed = {
    ["apple"] = true,
    ["banana"] = true,
    ["cherry"] = true,
}

-- O(1) lookup instead of scanning a list
if allowed[someValue] then
    print("found")
end
```
Reason: A keyed table acts like a set, so membership checks are direct hash lookups instead of `table.HasValue`'s linear scan.


```lua
local t = {
    a = 1,
    b = 2,
    c = 3,
}
```
Reason: The constructor is usually faster for a small table with known fields because it builds the table and fills the fields in one step, instead of creating an empty table and doing extra writes afterward.


```lua
local function RandomSequential(t)
    return t[math.random(#t)]
end
```
Reason: `table.Random` does extra work to handle non-sequential tables; for an array-like table, direct length plus indexed access is simpler and faster.


```lua
x * x
```
Reason: `x * x` is the direct, fastest readable way to square a number in Lua; it avoids function calls and extra overhead.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- visit each connected player here
end
```
Reason: `player.GetAll()` returns the current player list as an array, so `ipairs` is the direct loop for every connected player.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- process ent here
    end
end
```
Reason: `ents.Iterator()` walks entities lazily, so this filters `prop_physics` without building a full entity table first.


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


```lua
if not IsValid(ent) then return end
```
Reason: `IsValid` returns false for `nil`, removed, or invalid entities, so this guard prevents method calls on a dead reference.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming net message here
end)
```
Reason: `net.Receive` registers the incoming message handler for the named Garry's Mod net message.


```lua
local ZERO_ANGLE = Angle(0, 0, 0)

-- Hot path: reuse the same zero angle if the caller treats it as read-only.
local ang = ZERO_ANGLE
```
Reason: this avoids allocating a new Angle object on every call; if you need a mutable instance, reuse one scratch Angle and reset its fields instead of constructing a new one.


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

local function DrawSomething()
    local color = addon_color
end
```
Reason: A local/upvalue is faster to read than repeated table indexing like `myaddon.config.color`, so cache frequently read settings locally.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores job data in its own variable system, so `getDarkRPVar("job")` is the intended API instead of reading the networked string directly.


```lua
if pos1:DistToSqr(pos2) <= threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the expensive square root when you only need a threshold check.


```lua
for ent in ents.Iterator() do
    -- visit each entity
end
```
Reason: `ents.Iterator()` avoids building the full `ents.GetAll()` table first, so it is the efficient wiki-recommended way to visit every entity once.


```lua
local ply = player.GetHumans()[1]
if not IsValid(ply) then return end

local pos = ply:GetPos()
local radius = 512
local nearby = ents.FindInSphere(pos, radius)

for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) and ent ~= ply then
        -- cheap per-entity work here
    end
end
```
Reason: `ents.FindInSphere` is one of the faster built-in broad-phase queries for “nearby entities” in common GMod benchmarks, and it matches the player-radius use case without relying on `FindInPVS`.


```lua
local function FindPlayersInSphere(pos, radius)
    local radiusSqr = radius * radius
    local found = {}
    local players = player.GetAll()

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:GetPos():DistToSqr(pos) <= radiusSqr then
            found[#found + 1] = ply
        end
    end

    return found
end
```
Reason: `player.GetAll()` scans only players, and `DistToSqr` avoids a square root, so it is cheaper than `ents.FindInSphere` plus filtering entities.


```lua
local sum = 0
for i = 1, n do
    sum = sum + i
end
```
Reason: In Lua and Garry's Mod Lua, a numeric `for` loop is generally faster than an equivalent `while` loop because it uses a more optimized VM path and avoids repeated manual counter updates and comparisons.


```lua
-- Faster: one hook dispatch for all players
local players = player.GetAll()
hook.Run("MyTickPlayers", players)

-- Slower: one hook dispatch per player
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("MyTickPlayer", ply)
-- end
```
Reason: one hook.Run call avoids repeated hook lookup and Lua/C boundary overhead for every player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText("HP: " .. health, "DermaDefault", 20, 40, color_white)
    surface.DrawRect(20, 60, health, 10)
end)
```
Reason: Cache `LocalPlayer():Health()` once per frame and reuse the local value, so the hook avoids repeating the same lookup three times.


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

hook.Add("HUDPaint", "MyPaintLoop", function()
    for i = 1, 100 do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(i, i, 10, 10)
    end
end)
```
Reason: Hoisting the `Color(255, 255, 255)` allocation out of the loop avoids creating a new color object every iteration.


```lua
local sin = math.sin

for i = 1, n do
    total = total + sin(values[i])
end
```
Reason: `math.sin` is copied into a local once, so the hot loop uses a faster local lookup instead of repeated table indexing.


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

-- hot path
local ply = LP()
if IsValid(ply) then
    -- use ply
end
```
Reason: it caches the player entity and only calls `LocalPlayer()` again when the cached value is invalid, so repeated hot-path access avoids a fresh lookup each time.


```lua
-- Returns true when each player is aiming roughly toward the other.
-- threshold is cosine-based: 1.0 = exact, 0.95 ~= within 18 degrees.
local function ArePlayersRoughlyLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.95

    local pos1 = ply1:EyePos()
    local pos2 = ply2:EyePos()
    local dir12 = (pos2 - pos1)
    local lenSqr = dir12:LengthSqr()
    if lenSqr == 0 then return false end

    dir12:Normalize()

    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()

    return aim1:Dot(dir12) >= threshold and aim2:Dot(-dir12) >= threshold
end
```
Reason: Dot products give the same directional check without the cost of `math.acos`, so this stays cheap and branch-light.


```lua
SomeHelper(ply)
```
Reason: `ply:SomeHelper()` is sugar for `ply.SomeHelper(ply)` and does a lookup on `ply`, so a direct helper call is generally a bit faster for code you control.


```lua
MsgN("Think debug: ", value)
```
Reason: `MsgN` writes directly to the console with less formatting overhead than `print`, so it is cheaper in hot paths.