```lua
local n = #nums
for i = 1, n do
    local v = nums[i]
    -- use v
end
```
Reason: For a dense sequential array-like table, a numeric `for` is typically fastest because it avoids iterator overhead from `pairs`/`ipairs` and uses direct indexed access.


```lua
-- Faster than chaining DarkRP fn combinators: one pass, no intermediate arrays.
local function filter_map(src, keep, map)
    local out, n = {}, 0
    for i = 1, #src do
        local v = src[i]
        if keep(v) then
            n = n + 1
            out[n] = map(v)
        end
    end
    return out
end

-- Example: keep alive players, map to SteamID.
local ids = filter_map(players, function(p) return IsValid(p) and p:Alive() end, function(p) return p:SteamID() end)
```
Reason: One loop, one output table, and no chained combinator/closure overhead or intermediate list allocations.


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

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

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

hook.Add("Tick", "MyCachedPlayerLoop", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- fast per-player work here
    end
end)
```
Reason: `player.GetAll()` allocates a fresh table every call; caching it and refreshing only on join/leave removes that per-tick work.


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

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

local function GetTemp(ply)
    return tempByPly[ply]
end
```
Reason: `tempByPly[ply]` is a plain upvalue table lookup; it avoids storing on the entity object itself and is the better hot-read path for temporary per-player data.


```lua
local items = {
  "apple",
  "banana",
  "cherry",
}

for i = 1, #items do
  local value = items[i]
  -- process value
end
```
Reason: Sequential integer-indexed arrays are faster to iterate than string-keyed maps because Lua can use dense array storage and cheap numeric indexing, while maps require hash lookups per key.


```lua
surface.SetDrawColor(255, 80, 40, 255)
```
Reason: Passing raw RGBA numbers avoids Color table handling in a hot draw path.


```lua
local steamid = 'STEAM_0:1:12345'
local rows = sql.Query("SELECT points FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: For a single GMod server with no sync requirement, local SQLite is typically lower latency because it avoids network round trips and remote DB connection overhead.


```lua
local SteamIDCache = setmetatable({}, { __mode = "k" }) -- weak keys: players fall out automatically

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

-- Hot path use:
-- local sid = CachedSteamID(ply)
```
Reason: This memoizes the C++ `ply:SteamID()` call per player entity, so repeated lookups hit a Lua table instead of crossing the Lua/C boundary every time.


Answer must contain 0 through 0 candidate loops.

```lua
-- Slow:
-- local out = ""
-- for i = 1, #pieces do
--   out = out .. pieces[i]
-- end

-- Fast:
local function build_string(pieces)
  local out = {}
  for i = 1, #pieces do
    out[i] = pieces[i]
  end
  return table.concat(out)
end

local pieces = {}
for i = 1, 10000 do
  pieces[i] = tostring(i)
end

local result = build_string(pieces)
```
Reason: `table.concat` builds the final string in one pass, while repeated `..` creates many intermediate strings and copies.


```lua
surface.SetDrawColor(col)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is the direct solid-rectangle primitive, so it skips the extra rounded-box path and is a bit cheaper for plain non-rounded fills.


```lua
local font = "HUD_FastLine"

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

local function DrawFastLine(text, x, y, col)
    surface.SetFont(font)
    surface.SetTextColor(col.r, col.g, col.b, col.a or 255)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end

hook.Add("HUDPaint", "DrawFastLineExample", function()
    DrawFastLine("Single-line text", 100, 100, color_white)
end)
```
Reason: `surface.DrawText` with a cached font is the lightest path here; `draw.DrawText` adds extra layout work, and `draw.SimpleTextOutlined` is slower because it draws the text multiple times for the outline.


```lua
local n = #t
```
Reason: `#` is the standard Lua length operator for sequential array-like tables in Garry's Mod.


```lua
-- Generally faster when you can drop the old table entirely:
t = {}
```
Reason: `t = {}` only creates a new table and rebinds the variable, while `table.Empty(t)` has to walk and clear the existing table; use `table.Empty(t)` only when other references must keep seeing the same table.


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

if allowed[value] then
    print("exists")
end
```
Reason: `table.HasValue` scans the whole list, while a key lookup in a set-like table is direct and faster.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: In Lua, a table constructor does the allocation and field setup in one step, while `local t = {}; t.x = 1; t.y = 2; t.z = 3` does extra assignments after creation, so the constructor is usually faster for small known tables.


```lua
local function FastRandomElement(t)
    return t[math.random(#t)]
end
```
Reason: `table.Random` handles arbitrary tables, while sequential tables can use direct indexed lookup with `math.random(#t)` and avoid the extra scan.


```lua
x * x
```
Reason: `x * x` avoids a function call and is the fastest simple way to square a number in Lua.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- visit each connected player here
end
```
Reason: `player.GetAll()` returns the current connected players as an array-like table, so `ipairs` iterates them in order.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent here
    end
end
```
Reason: It streams entities with `ents.Iterator()` and filters by class, so it does not build `ents.GetAll()` first.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers `MyAddon.Think` as the named callback for the `Think` hook.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid` is the standard Garry's Mod guard for entity references, and it returns false when the entity is nil, removed, or otherwise invalid.


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


```lua
-- avoid this in tight loops:
-- local ang = Angle()

local ang = angle_zero
```
Reason: `angle_zero` is a prebuilt zero Angle, so you skip per-call Angle userdata allocation in the hot path.


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

print(addon_color)
```
Reason: a local/upvalue read is faster than repeated nested table lookups, and faster than a global read too.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP exposes job as a DarkRPVar, so this uses the framework accessor instead of reading the underlying NW string directly.


```lua
if pos1:DistToSqr(pos2) <= (range * range) then
    -- within range
end
```
Reason: `DistToSqr` skips the square root, so it is the right choice for threshold checks.


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


```lua
local function GetNearbyEnts(ply, radius)
    local pos = ply:GetPos()
    local offset = Vector(radius, radius, radius)
    return ents.FindInBox(pos - offset, pos + offset)
end
```
Reason: `ents.FindInBox` is a cheap axis-aligned spatial query and is generally one of the faster built-in `FindIn*` options for nearby-entity checks, especially when you do not need `FindInPVS`.


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

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

    return result
end
```
Reason: `player.GetAll()` scans only players instead of every entity, and `DistToSqr` avoids the square-root cost from full distance checks.


```lua
for i = 1, n do
    -- tight loop body
end
```
Reason: Numeric `for` is generally faster than `while` in GMod Lua/LuaJIT because the VM can run it with less per-iteration bookkeeping.


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

-- Slower: one hook dispatch per player
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("MyCustomTick", ply)
-- end
```
Reason: `hook.Run` has dispatch overhead; calling it once and handling all players in the hook avoids repeated per-player hook lookups and calls.


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

    local health = lp:Health()

    draw.SimpleText(health, "Trebuchet18", 20, 20, color_white)
    draw.SimpleText(health, "Trebuchet18", 20, 40, color_white)
    draw.SimpleText(health, "Trebuchet18", 20, 60, color_white)
end)
```
Reason: `LocalPlayer()` and `:Health()` are evaluated once, then reused by all three draw calls instead of repeating the same lookup three times each frame.


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

hook.Add("HUDPaint", "MyPaintLoop", function()
    for i = 1, 100 do
        surface.SetDrawColor(WHITE)
        -- draw stuff here
    end
end)
```
Reason: Hoisting the color object avoids allocating a new table on every loop iteration.


```lua
local sin = math.sin

for i = 1, 100000 do
    local x = sin(i)
end
```
Reason: `local sin = math.sin` hoists the table lookup out of the hot loop, so each iteration calls a local instead of resolving `math.sin` repeatedly.


```lua
local GetLocalPlayer = LocalPlayer
local lp = GetLocalPlayer()

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

    -- use `lp` here instead of calling LocalPlayer() repeatedly
end)
```
Reason: caching the global function in a local and reusing one player reference avoids repeated global lookup and repeated `LocalPlayer()` calls in hot code.


```lua
local function PlayersLookingAtEachOther(ply1, ply2, dotThreshold)
    dotThreshold = dotThreshold or 0.90 -- higher = stricter, about 25 degrees

    local delta = ply2:GetShootPos() - ply1:GetShootPos()
    local distSqr = delta:LengthSqr()
    if distSqr == 0 then return false end

    local dir = delta / math.sqrt(distSqr)
    return ply1:GetAimVector():Dot(dir) >= dotThreshold
       and ply2:GetAimVector():Dot(-dir) >= dotThreshold
end
```
Reason: Dot product is the cheap test here: it avoids `math.acos` and gives a fast threshold check for whether each aim vector points toward the other player.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally a bit faster because `ply:SomeHelper()` adds a method lookup and implicit `self` passing, so the plain function call is the cheaper direct path.


```lua
MsgN("[dbg] hot path hit")
```
Reason: `MsgN` writes straight to the console and avoids `print`'s extra formatting work.


```lua
local n = #numbers
for i = 1, n do
    local v = numbers[i]
    -- use v
end
```
Reason: A numeric `for` is typically fastest for a dense sequential array in Garry's Mod Lua; `ipairs` adds iterator overhead and `pairs` is slower and not the right fit for array-only traversal.


```lua
local function filterMap(src, keep, map)
    local out = {}
    local n = 0

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

    return out
end

-- Example: keep alive players and turn them into names.
local names = filterMap(player.GetAll(), function(p)
    return p:Alive() and p:GetNWBool("ready", false)
end, function(p)
    return p:Nick()
end)
```
Reason: This fuses filter and map into one numeric loop, so it avoids the extra intermediate tables and closure dispatch that DarkRP's `fn` combinators add.


```lua
-- Server-side player cache: rebuild only when roster changes.
local cachedPlayers = player.GetAll()

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

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

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

        if IsValid(ply) then
            -- your per-player tick logic here
        end
    end
end)
```
Reason: `player.GetAll()` allocates a fresh table; caching it and refreshing only on join/leave removes that work from every tick.


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

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

local function GetTemp(ply)
    return tempByPly[ply]
end
```
Reason: `tempByPly[ply]` is a plain upvalue-table lookup, which is usually faster on reads than entity field access, and weak keys keep it temporary.


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

for i = 1, #values do
  local value = values[i]
end
```
Reason: sequential number-indexed arrays are faster to iterate than string-keyed maps because Lua can walk them with simple numeric indexing instead of hash lookups on string keys.


```lua
surface.SetDrawColor(255, 80, 40, 255)
```
Reason: Passing raw `r, g, b, a` numbers avoids the `Color` object/table path and is the leaner call in a hot draw loop.


```lua
local steamid = ply:SteamID64()
local row = sql.Query("SELECT kills, deaths FROM player_stats WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: On a single server with no sync requirement, local SQLite is typically lower latency because it avoids network round-trips and remote connection overhead.


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

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

-- hot path
for _, ply in ipairs(player.GetAll()) do
    local steamid = SteamIDCached(ply)
    -- use steamid
end
```
Reason: `SteamID()` is stable per player, so memoizing it once per player avoids repeated Lua-to-engine calls in the hot path.


```lua
local parts = {}

for i = 1, 10000 do
    parts[#parts + 1] = get_piece(i)
end

local big = table.concat(parts)
```
Reason: `table.concat` joins all pieces in one pass, avoiding the repeated reallocations and copies caused by `s = s .. piece` in a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, so it avoids the extra rounded-box path that `draw.RoundedBox(0, ...)` still goes through.


```lua
hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("Trebuchet18")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText("Single-line text")
end)
```
Reason: `surface.DrawText` is the lowest-level path here, so it skips the extra alignment and wrapper work in `draw.DrawText`, and it avoids the multiple extra passes that `SimpleTextOutlined` does.


```lua
local len = #myTable
```
Reason: `#` is the standard Lua length operator for sequential array-like tables.


```lua
t = {}
```
Reason: `t = {}` is generally faster because it only rebinds the variable to a fresh table; `table.Empty(t)` has to clear the existing table in place, which costs more when the table is large. Use `table.Empty(t)` only if other references must see the same table emptied.


```lua
local allowed = {
    ["prop_physics"] = true,
    ["npc_combine_s"] = true,
    ["npc_zombie"] = true,
}

if allowed[ent:GetClass()] then
    -- exists in the set
end
```
Reason: `allowed[value]` is a constant-time hash lookup, while `table.HasValue` walks the list linearly.


```lua
local t = {
  foo = 1,
  bar = 2,
}
```
Reason: The table constructor creates and fills the table in one step, so it avoids separate field assignments.


```lua
local function RandomSequential(t)
    return t[math.random(#t)]
end
```
Reason: `table.Random` walks the table to pick a value, while a sequential array can use `#t` plus direct indexing in O(1).


```lua
local y = x * x
```
Reason: `x * x` is the fastest, simplest square in Lua; it avoids function-call overhead from `math.pow`.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- do something with ply
end
```
Reason: `player.GetAll()` returns the current players as an array, so `ipairs` visits each connected player directly.


```lua
for ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- visit the prop_physics entity
    end
end
```
Reason: `ents.Iterator()` streams entities directly from the engine so you avoid creating a full entity table first (unlike `ents.GetAll()`/`ents.FindByClass`).


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback logic
end)
```

Reason: `hook.Add` uses a string identifier to bind/removal-track the callback, and using `"MyAddon.Think"` gives you that unique callback handle on the `Think` hook.


```lua
if IsValid(ent) then
    ent:YourMethod()
end
```
Reason: `IsValid` is the Garry's Mod helper that returns false for nil, removed entities, and invalid handles, so it prevents calling methods on unsafe references.


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

    net.Receive("MyAddon.Sync", function(len, ply)
        local payload = net.ReadString()
        print("Received from", ply:Nick(), payload)
    end)
end
```
Reason: Use `util.AddNetworkString` on the server and `net.Receive("MyAddon.Sync", ...)` to register the callback for incoming messages.


```lua
-- Allocate once, zero on demand in place
local zeroAng = Angle(0, 0, 0)

local function getZeroAngle()
    zeroAng.p, zeroAng.y, zeroAng.r = 0, 0, 0
    return zeroAng
end

-- hot-path call
local ang = getZeroAngle()
ent:SetAngles(ang)
```
Reason: Reusing a single preallocated `Angle` avoids constructing a new Lua userdata every hot-path iteration, which is the costly part, and only updates three numeric fields (`p`,`y`,`r`) each call.


```lua
local COLOR_SETTING = myaddon.config.color -- cache once at load/init time
local function Draw()
    local c = COLOR_SETTING
    -- use c in hot path
end
```
Reason: A flat local (`COLOR_SETTING`) is fastest because Lua resolves locals by fast stack lookup and avoids repeated global+table chain lookups (`_G`, `myaddon`, `config`, `color`) each read; globals and nested tables add extra pointer/hash overhead per access, especially in hot loops.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: In DarkRP, `getDarkRPVar("job")` is the canonical accessor for role data and works with DarkRP’s networked var system, while `ply:GetNWString("job")` is a raw NW var call and can drift from DarkRP’s job tracking and is deprecated style.


```lua
local posA = Vector(10, 0, 0)
local posB = Vector(13, 4, 0)
local maxDist = 5

if posA:DistToSqr(posB) <= maxDist * maxDist then
    print("within threshold")
end
```
Reason: `DistToSqr` compares squared distance directly, avoiding the expensive square-root call from `Distance` while giving the same threshold result by squaring the threshold once.


```lua
-- Fastest canonical walk for all entities
for ent in ents.Iterator() do
    if IsValid(ent) then
        -- Visit every entity here
        print(ent:GetClass(), ent:EntIndex())
    end
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient path because it avoids allocating an intermediate table like `ents.GetAll()`, which is preferable for full-entity scans.


```lua
-- Fast nearby entities from a player position, server-side
local function GetNearbyEntitiesCheap(ply, radius)
    local origin = ply:GetPos()
    local half = Vector(radius, radius, radius)

    local candidates = ents.FindInBox(origin - half, origin + half)

    local near = {}
    local radiusSq = radius * radius

    for i = 1, #candidates do
        local ent = candidates[i]
        if IsValid(ent) and ent ~= ply then
            local delta = ent:GetPos() - origin
            if delta:LengthSqr() <= radiusSq then
                near[#near + 1] = ent
            end
        end
    end

    return near
end
```
Reason: `ents.FindInBox` is commonly faster for proximity checks than `ents.FindInSphere` in GMod benchmarks because it performs a tight AABB broad phase first, then a cheap squared-distance filter removes false positives without trig/sqrt overhead.


```lua
local function GetPlayersWithinRadius(pos, radius)
    local players = player.GetHumans()  -- or player.GetAll() if you want bots too
    local radiusSq = radius * radius
    local out = {}

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

    return out
end
```
Reason: You avoid scanning all nearby entities via ents.FindInSphere and only iterate over player entities directly, replacing one broad spatial query and broad per-entity filtering with a bounded player-only pass.


```lua
local n = 1000000
local sum = 0

for i = 1, n do
    sum = sum + i
end
```
Reason: In Garry's Mod Lua, `for i = 1, n do` is generally faster than an equivalent `while` loop because the VM executes numeric `for` as an optimized opcode sequence, reducing per-iteration overhead versus manual increment/check logic.


```lua
-- Faster: one hook dispatch per tick, not one per player.
hook.Add("Think", "NotifyAllPlayersTick", function()
    local players = player.GetAll()
    hook.Run("HandlePlayersTick", players)
end)

hook.Add("HandlePlayersTick", "MyPlayerNotify", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom per-player logic here
    end
end)
```
Reason: `hook.Run` has global dispatch overhead, so one call with the full player array is cheaper than N calls on the same tick; the per-player work stays in one predictable loop inside the handler.


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

    local hp = ply:Health()
    local maxHp = ply:GetMaxHealth()

    draw.RoundedBox(0, 20, 20, maxHp, 12, Color(30, 30, 30, 200))
    draw.RoundedBox(0, 20, 20, hp, 12, Color(0, 200, 0, 220))
    draw.SimpleText("HP: " .. hp .. "/" .. maxHp, "DermaLarge", 20 + maxHp / 2, 36, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP)
end)
```
Reason: Cache the player entity and health values once before the three draw calls so you avoid three expensive `LocalPlayer():Health()` lookups in one frame.


```lua
-- Create once, not every paint iteration
local WHITE = Color(255, 255, 255, 255)

local function drawHUD()
    local setColor = surface.SetDrawColor
    local drawRect = surface.DrawRect

    -- call once per frame, not per item
    setColor(WHITE)

    for i = 1, 100 do
        drawRect(i * 3, 20, 2, 20)
    end
end

hook.Add("HUDPaint", "FastWhiteRects", drawHUD)
```
Reason: Color() allocates a new color object each call, so cache it once (or use numeric args) and reuse it, and move SetDrawColor outside the loop to avoid redundant calls.


```lua
local sin = math.sin

local function tick(values, t)
    local s = sin
    for i = 1, #values do
        local v = values[i]
        values[i] = s(v + t) -- local upvalue lookup, no repeated math table/index lookup
    end
    return values
end
```
Reason: Hoist `math.sin` into a local once and use that local inside the hot loop so each iteration avoids repeated global/table lookups (`math` and field access) and pays only the function call overhead.


```lua
-- Client-side: cache LocalPlayer() in module scope
local lp

local function getLocalPlayerCached()
    if not lp or not IsValid(lp) then
        lp = LocalPlayer()
    end
    return lp
end

hook.Add("InitPostEntity", "cache_local_player", function()
    lp = LocalPlayer()
end)

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

    -- use lp here instead of LocalPlayer()
    local ply = lp
    if ply:Alive() then
        -- do stuff
        -- ply:SetRunSpeed(250)
    end
end)

hook.Add("OnPlayerDisconnected", "clear_local_player_cache", function()
    lp = nil
end)
```
Reason: Keep `LocalPlayer()` in a local cached reference and only re-fetch on initialization or invalidation, so normal callsites read one upvalue instead of repeating global lookups every tick/function call.


```lua
local DOT_LIMIT = 0.8660254 -- cos(30°)
local DOT_LIMIT2 = DOT_LIMIT * DOT_LIMIT

local function playersRoughlyFacingEachOther(plyA, plyB)
    local aA = plyA:GetAimVector()
    local aB = plyB:GetAimVector()

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

    local dA = aA:Dot(delta)
    if dA <= 0 or dA * dA < DOT_LIMIT2 * dist2 then return false end

    local dB = aB:Dot(-delta)
    if dB <= 0 or dB * dB < DOT_LIMIT2 * dist2 then return false end

    return true
end
```
Reason: It avoids `acos` by checking both players' aim vectors against the target direction with dot products, using squared-dot vs squared-threshold comparisons to skip vector normalization and expensive trig.


```lua
-- Preferred for speed + flexibility when you control the helper
local function SomeHelper(ply)
    -- helper body
end

SomeHelper(ply)
```
Reason: Method-call syntax (`ply:SomeHelper()`) is just sugar for `ply.SomeHelper(ply)`, so they compile to the same argument-passing form; use the plain function form when possible to avoid extra table lookup and keep intent clear.


```lua
local log = Msg -- cache global once for hot-path calls

local function DebugLine(msg)
    log(tostring(msg))
    log("\n")
end

-- hot path
DebugLine("spawned " .. ent:EntIndex())
```
Reason: `print` does table-like formatting and newline/arg handling each call, while `Msg`/`MsgN` writes directly to console with lower overhead in Garry's Mod.


```lua
local sum = 0
local n = #arr
for i = 1, n do
    local v = arr[i]
    sum = sum + v
end
```
Reason: Numeric `for` over contiguous indices (`1 .. #arr`) is typically fastest for array-like numeric tables in Garry's Mod Lua because it avoids iterator closures and hash traversal overhead, while `pairs`/`ipairs` add iterator function calls and extra runtime checks each step.


```lua
-- Fast 1-pass filter/map pipeline (faster than fn.filter/fn.map chains)
local function buildTopSalaryPayouts()
    local src = player.GetAll()
    local dst = {}
    local n = 0

    for i = 1, #src do
        local ply = src[i]
        if ply:IsPlayer() and ply:Alive() and ply:Team() == TEAM_CITIZEN then
            local money = ply:getDarkRPVar("money")

            if money and money > 2500 then
                n = n + 1
                dst[n] = {
                    id = ply:SteamID64(),
                    name = ply:Nick(),
                    payout = money * 0.2,
                }
            end
        end
    end

    return dst
end

local topSalaryPayouts = buildTopSalaryPayouts()
```
Reason: one-pass imperative loop fuses multiple filter/map steps, builds only one output table, and avoids fn combinator iterator/function-call overhead in Tight loops.


```lua
local activePlayers = {}
local playerIndex = {}

local function AddCachedPlayer(ply)
    if not IsValid(ply) or not ply:IsPlayer() or playerIndex[ply] then return end

    playerIndex[ply] = #activePlayers + 1
    activePlayers[#activePlayers + 1] = ply
end

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

    local last = #activePlayers
    local swapped = activePlayers[last]

    activePlayers[idx] = swapped
    playerIndex[swapped] = idx

    activePlayers[last] = nil
    playerIndex[ply] = nil
end

local function SyncPlayers()
    for _, ply in ipairs(player.GetAll()) do
        AddCachedPlayer(ply)
    end
end

hook.Add("Initialize", "PlayerCache.Init", function()
    SyncPlayers()
end)

hook.Add("PlayerInitialSpawn", "PlayerCache.Add", AddCachedPlayer)
hook.Add("PlayerDisconnected", "PlayerCache.Remove", RemoveCachedPlayer)

hook.Add("Think", "PlayerCache.Think", function()
    for _, ply in ipairs(activePlayers) do
        -- fast per-tick work over active players
        -- do your tick logic with ply
    end
end)
```
Reason: It replaces per-tick `ipairs(player.GetAll())` with a maintained cache updated only on `PlayerInitialSpawn`/`PlayerDisconnected`, so Think iterates the live player list in O(n) without rebuilding it every frame.


```lua
-- Fast per-player scratch storage keyed by entity index (faster than ply.someField)
local tempByEnt = {}

local function getState(ply)
    local id = ply:EntIndex()               -- integer key lookup (faster than string field on entity)
    local s = tempByEnt[id]
    if s then return s end

    s = {score = 0, last = 0}
    tempByEnt[id] = s
    return s
end

local function setState(ply, k, v)
    getState(ply)[k] = v
end

hook.Add("Think", "PlayerPerfHotPath", function()
    for _, ply in ipairs(player.GetHumans()) do
        local st = getState(ply)             -- one table lookup for all hot fields
        st.score = st.score + 1
        local s = st.score                   -- repeated reads are now from local table
    end
end)

hook.Add("PlayerDisconnected", "CleanupTempByEnt", function(ply)
    tempByEnt[ply:EntIndex()] = nil
end)
```
Reason: Use a per-player table-of-tables keyed by `EntIndex()` and reuse that reference in hot loops to avoid dynamic property access on the player entity (`ply.someField`) each time, which is significantly slower and noisier for repeated reads.


Answer must contain 0 through 1 candidate loops.

```lua
-- Preferred iteration shape: contiguous numeric keys (array), not string-keyed map.
local function count_len_array()
    local a = {
        1, 2, 3, 4, 5,
        6, 7, 8, 9, 10,
    }

    local sum = 0
    for i = 1, #a do
        sum = sum + a[i]
    end
    return sum
end

local function count_len_map()
    local m = {
        one = 1,
        two = 2,
        three = 3,
        four = 4,
        five = 5,
        six = 6,
        seven = 7,
        eight = 8,
        nine = 9,
        ten = 10,
    }

    local sum = 0
    for _, v in pairs(m) do
        sum = sum + v
    end
    return sum
end

-- Usage note: use #index loops / ipairs for arrays, pairs only when keys are non-contiguous or non-numeric.
```
Reason: Use number-indexed sequential arrays with `#`/`for i` (or `ipairs`) because Lua stores them in the array part and can iterate with low-overhead pointer-like traversal, while string-keyed maps use hash-table iteration which is slower and unordered.


```lua
local r, g, b, a = 255, 255, 255, 255

local function DrawHot(x, y, w, h)
    for i = 0, 1000 do
        surface.SetDrawColor(r, g, b, a)
        surface.DrawRect(x, y + i, w, h)
    end
end
```
Reason: Passing raw `r, g, b, a` arguments in the hot loop is faster than building/using a `Color` object, which avoids table/metadata overhead each draw call.


```lua
local sid = player:SteamID64()
local row = sql.QueryRow("SELECT money FROM player_data WHERE steamid64 = " .. sql.SQLStr(sid))
if row then
    print("money:", row.money)
end
```
Reason: For a single Garry's Mod server with no cross-server sync, local SQLite via the built-in `sql` module is typically lower latency than remote MySQL because it avoids network roundtrips and extra connection/query overhead for every read/write.


```lua
-- Fast cache for repeated SteamID lookups on hot paths.
local steamIdCache = setmetatable({}, { __mode = "k" }) -- weak keys, auto-clean on disconnect

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

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

    sid = ply:SteamID() -- expensive-ish when called many times per frame
    steamIdCache[ply] = sid
    return sid
end

-- Optional: prewarm cache when the player enters
hook.Add("PlayerInitialSpawn", "PrewarmSteamIDCache", function(ply)
    steamIdCache[ply] = ply:SteamID()
end)

-- Hot path:
-- use GetSteamIDCached(ply) instead of ply:SteamID()
local function SomeHotPath(ply)
    local sid = GetSteamIDCached(ply)
    -- do stuff using sid
end
```
Reason: Cache by player object in a weak-key table and hydrate once, so repeated hot-path calls reuse the same SteamID string and avoid repeated native lookups.


```lua
-- Build many small pieces
local pieces = {}
for i = 1, 5000 do
    pieces[i] = "piece_" .. i .. " "
end

-- Fast: build an array and join once
local text = table.concat(pieces, "")

-- Equivalent old pattern (slow for many iterations)
-- local text2 = ""
-- for i = 1, #pieces do
--     text2 = text2 .. pieces[i]
-- end
```
Reason: Use `table.concat` to append once with linear cost and avoid O(n^2) reallocation behavior from repeated `..` concatenation in Lua.


```lua
-- faster replacement: direct rect draw when radius is always 0
local SetDrawColor = surface.SetDrawColor
local DrawRect = surface.DrawRect

local function DrawFlatRects(rects)
    for i = 1, #rects do
        local r = rects[i]
        SetDrawColor(r.r, r.g, r.b, r.a)
        DrawRect(r.x, r.y, r.w, r.h)
    end
end
```
Reason: `draw.RoundedBox(0, ...)` still routes through rounded-box path and table-based draw helpers, while `surface.SetDrawColor` + `surface.DrawRect` is the direct non-rounded primitive and avoids that overhead.


```lua
if not surfaceFont then
    surface.CreateFont("FastSingleLine", {
        font = "Roboto",
        size = 18,
        weight = 500,
        antialias = true,
        additive = false,
    })
    surfaceFont = true
end

local txt = "Health: " .. LocalPlayer():Health()
local x, y = 16, 16

hook.Add("HUDPaint", "FastSingleLineText", function()
    local c = Color(255, 255, 255, 220) -- cache this in a local/ambient if you can

    surface.SetFont("FastSingleLine")
    surface.SetTextColor(c.r, c.g, c.b, c.a)
    surface.SetTextPos(x, y)
    surface.DrawText(txt)
end)
```
Reason: `surface.DrawText` is the fastest for per-frame single-line text because it is the low-level text path and skips the extra argument, style, and outline/shadow processing done by `draw.DrawText`/`SimpleTextOutlined`.


```lua
local t = {"a", "b", "c"}
local n = #t
```
Reason: Use the length operator `#` (`local n = #t`) for sequential array-like tables; it returns the array length in Garry's Mod Lua.


```lua
-- Prefer rebind when you only need to drop the current contents.
-- This is typically faster than table.Empty for large tables.

local function resetSequential(t)
    t = {}      -- O(1): replaces the table reference
    return t
end

myTable = resetSequential(myTable)
```
Reason: `t = {}` is usually faster because it replaces the table in constant time, while `table.Empty(t)` must iterate and nil each element in `O(n)`; use `table.Empty` only when other references to the same table must stay valid.


```lua
-- Slow: scans every item until match
local function hasValueList(list, needle)
    return table.HasValue(list, needle)
end

-- Fast: constant-time set lookup
local function buildSet(list)
    local set = {}
    for _, value in ipairs(list) do
        set[value] = true
    end
    return set
end

local blacklist = buildSet({"smg1", "ar2", "crossbow"})

local function hasValueSet(set, needle)
    return set[needle] == true
end

-- Usage
print(hasValueSet(blacklist, "ar2"))      -- true
print(hasValueSet(blacklist, "physgun"))  -- false
```
Reason: Convert the source list once into a key-indexed table and use O(1) key lookup instead of O(n) scanning on every check.


```lua
-- Faster: build all known fields in one constructor.
local t = {
    hp = 100,
    armor = 50,
    name = "Pilot"
}
```
Reason: A literal table constructor allocates and populates entries in one step, which avoids extra table writes/lookups from `{}` plus `t.hp = ...` assignments and is the idiomatic fast path in Lua/GLua.


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

-- usage
local pick = randomSequential(myArray)
```
Reason: `table.Random` must inspect keys and hashes them, while numeric-indexed tables can use `#t` plus one `math.random` and O(1) direct index lookup for the common array case.


```lua
local function processLoop(xs)
    local acc = 0
    for i = 1, #xs do
        local x = xs[i]
        local sq = x * x
        acc = acc + sq
    end
    return acc
end
```
Reason: In a tight Garry's Mod Lua loop, `x * x` is the preferred fast form for squaring because it is a direct arithmetic multiply with no exponent operator or `math.pow` call overhead.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- do something with ply
end
```
Reason: `player.GetAll()` returns the active player list, and iterating it once visits every currently connected player.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    if IsValid(ent) then
        -- process ent
    end
end
```
Reason: `ents.FindByClass` directly returns only `prop_physics` entities, so the loop visits only that class without first building a full-map entity list.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers the callback to execute on every frame via `Think`, and `MyAddon.Think` is the hook identifier string used to track/overwrite/remove this hook later.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: `IsValid(ent)` is the canonical GMod validity check and guarantees `ent` is non-nil and not a NULL/removed entity before calling methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadString()
    -- handle data from the message here
end)
```
Reason: `net.Receive` registers a callback for that net message name so your function executes automatically when `MyAddon.Sync` arrives over the network.


```lua
local _zeroAngle = Angle(0, 0, 0) -- one allocation, done once

local function GetZeroAngle()
    _zeroAngle.p = 0
    _zeroAngle.y = 0
    _zeroAngle.r = 0
    return _zeroAngle
end

-- hot path:
-- local a = GetZeroAngle()
```
Reason: Reusing a preallocated Angle and zeroing its fields in-place avoids repeated `Angle()` construction and allocator/GC overhead, which is the usual hot-path win in Garry's Mod Lua.


```lua
-- cache once at load time
local addon_color = myaddon.config.color

-- frequent read
local color = addon_color
```
Reason: A flat local variable is fastest because it avoids repeated `global -> table -> field` lookups (`myaddon.config.color`), so frequent reads hit only a local access.


```lua
-- Prefer this in DarkRP:
local jobName = ply:getDarkRPVar("job")

-- (legacy Raw NWString equivalent):
-- local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is the DarkRP-specific accessor for player darkrp vars, kept in sync with job updates and more stable than reading raw NW strings directly.


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

if p1:DistToSqr(p2) < maxDistance * maxDistance then
    -- they are within range
end
```
Reason: Use `Vector:DistToSqr` for threshold checks because it compares squared distance and avoids the costly square-root in `Distance()`.


Answer must contain 1 through 1 candidate loops.

```lua
if ents.Iterator then
    for ent in ents.Iterator() do
        -- do something with ent
        print(ent:GetClass())
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- do something with ent
        print(ent:GetClass())
    end
end
```
Reason: Uses `ents.Iterator()` first as the efficient per-tick entity traversal pattern, with `ents.GetAll()` fallback only if the iterator is unavailable.


```lua
-- Server-side: cheap nearby-entity query (AABB prefilter) around a player
local function GetNearbyEntities(ply, radius)
    local origin = ply:GetPos()
    local ext = Vector(radius, radius, radius)
    local mins = origin - ext
    local maxs = origin + ext

    local sphereSq = radius * radius
    local result = {}

    -- faster FindIn* choice: ents.FindInBox + exact radius filter
    for _, ent in ipairs(ents.FindInBox(mins, maxs)) do
        if ent ~= ply and ent:GetPos():DistToSqr(origin) <= sphereSq then
            result[#result + 1] = ent
        end
    end

    return result
end

local nearby = GetNearbyEntities(player.GetByID(1), 768)
```
Reason: Using `ents.FindInBox` gives a fast engine-side broadphase pass, then a single squared-distance check keeps only entities within the true sphere radius without the heavier PVS path.


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

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

    return out
end
```
Reason: `ents.FindInSphere` scans all entities and allocates a larger result set, while iterating `player.GetAll()` (or `player.GetHumans()`) and using `DistToSqr` keeps work proportional to players only and avoids expensive sqrt in distance checks.


```lua
local n = 1000000
local sum = 0

for i = 1, n do
    sum = sum + i
end
```
Reason: `for i = 1, n do` is usually faster in Garry's Mod Lua because numeric `for` is a built-in optimized loop form, while a manual `while` loop pays extra Lua-level increment and branch overhead.


```lua
local function processPlayers(players, now, dt)
    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) then
            -- per-player custom logic
        end
    end
end

hook.Add("Think", "Tick_AllPlayersOnce", function()
    local players = player.GetAll()
    if #players == 0 then return end

    hook.Run("OnPlayersTick", players, CurTime(), FrameTime())
end)

hook.Add("OnPlayersTick", "CustomPlayerTick", function(players, now, dt)
    processPlayers(players, now, dt)
end)
```
Reason: One `hook.Run` call per tick does a single callback dispatch, so you avoid the O(n) hook-invocation overhead of calling `hook.Run` per player; per-player work stays in one loop you control.


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

    local hp = ply:Health()
    local hpText = "HP: " .. hp
    local hpClamped = math.Clamp(hp, 0, 100)

    draw.SimpleText(hpText, "DermaLarge", 24, 24, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.RoundedBox(0, 24, 56, 200, 16, Color(0, 0, 0, 180))
    draw.RoundedBox(0, 24, 56, hpClamped * 2, 16, Color(0, 180, 0, 220))
    draw.SimpleText(hpClamped .. "%", "DermaLarge", 24, 80, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```
Reason: Cache `LocalPlayer()` and `Health()` once per frame, then reuse `hp` across all three draw operations instead of calling `LocalPlayer():Health()` three times.


```lua
local WHITE = color_white -- built-in Color(255, 255, 255, 255)
local SetDrawColor = surface.SetDrawColor
local DrawRect = surface.DrawRect

hook.Add("HUDPaint", "PaintBars", function()
    SetDrawColor(WHITE) -- set once per paint call, not per iteration

    for i = 1, #rects do
        local r = rects[i]
        DrawRect(r.x, r.y, r.w, r.h)
    end
end)
```
Reason: Cache a `Color` (or use `color_white`) once and avoid creating one every loop iteration, while also moving `SetDrawColor` out of the inner loop to reduce per-item overhead.


```lua
local sin = math.sin

for i = 1, 1000000 do
    local v = sin(i * 0.01)
    -- ... use v
end
```
Reason: `sin` as a local is fetched once from `math` and then called directly, avoiding repeated global `_ENV` lookup (`math` table lookup + field access) on every loop iteration.


```lua
local lp

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

hook.Add("Think", "CacheLocalPlayer", function()
    cacheLocalPlayer()
end)

-- Hot path: no LocalPlayer() call anymore
local function updateHUD()
    if not lp or not lp:IsValid() then return end

    local pos = lp:GetPos()
    local vel = lp:GetVelocity()
    -- ... fast per-frame/client logic
end
hook.Add("Think", "MyFastLoop", updateHUD)
```
Reason: Cache `LocalPlayer()` in an upvalue once (or when it becomes invalid) and reuse that variable in hot loops so each frame logic avoids repeated global entity lookup.


```lua
local COS_45 = 0.7071068 -- cos(45°): adjust for tighter/looser cone

local function ArePlayersRoughlyFacingEachOther(p1, p2)
    local toP2 = p2:GetShootPos() - p1:GetShootPos()
    if toP2:LengthSqr() <= 0 then return false end

    toP2:Normalize() -- unit vector p1 -> p2

    local f1 = p1:EyeAngles():Forward():Dot(toP2)   -- p1 aiming at p2
    local f2 = p2:EyeAngles():Forward():Dot(-toP2)  -- p2 aiming at p1

    return f1 >= COS_45 and f2 >= COS_45
end

if ArePlayersRoughlyFacingEachOther(p1, p2) then
    -- mutual-ish eye contact
end
```
Reason: Use a normalized vector between players and compare both players' forward-dot-direction against a cosine threshold, which is a constant-time, no-`acos` check.


```lua
SomeHelper(ply)
```
Reason: No meaningful speed win for `ply:SomeHelper()` on a self-pass helper since `:` is just Lua sugar (`obj:fn(...) -> obj.fn(obj, ...)`), so for an internal helper `SomeHelper(ply)` is usually the better explicit call (use `:` only when you mean a real method API).


```lua
-- Faster console logging in hot paths for Garry's Mod Lua
local console = MsgN

if should_debug then
    console("[DBG] ", CurTime(), " state=", state, " pos=", myPos)
end
```
Reason: `MsgN` is the GMod-native console writer and is lighter than `print` because it avoids `print`'s heavier Lua formatting path and is intended for frequent debug output.


```lua
local nums = {...} -- large sequential array-like table

local n = #nums
local sum = 0

for i = 1, n do
    local v = nums[i]
    sum = sum + v
end
```
Reason: Use a numeric `for` with cached `#nums` because it is a direct indexed loop with no iterator overhead (`pairs`/`ipairs` allocate closures/calls per step), and is the fastest option for dense arrays in Luau/Lua 5.1 used by Garry's Mod.


```lua
local function getAlivePlayerNames(players)
    local out = {}
    local outN = 0

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

        -- filter -> map -> filter -> map, all in one loop
        if IsValid(ply) and ply:Alive() then
            local name = ply:Nick()
            if name ~= "" then
                outN = outN + 1
                out[outN] = string.lower(name)
            end
        end
    end

    return out
end

local names = getAlivePlayerNames(player.GetAll())
```
Reason: This keeps the pipeline in a single numeric for-loop, avoids creating nested iterator wrappers and temporary tables from fn combinators, and reduces function call overhead.


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

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

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

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

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

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

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

local function rebuildCache()
    table.Empty(cachedPlayers)
    table.Empty(playerIndex)
    for _, ply in ipairs(player.GetAll()) do
        cacheAdd(ply)
    end
end

hook.Add("Initialize", "MyPlayerCacheInit", rebuildCache)
hook.Add("PlayerInitialSpawn", "MyPlayerCacheAdd", cacheAdd)
hook.Add("PlayerDisconnected", "MyPlayerCacheRemove", cacheRemove)

hook.Add("Think", "MyTick", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- per-tick logic on cached players
        end
    end
end)
```
Reason: Keeps one player list in memory and updates it only on PlayerInitialSpawn/PlayerDisconnected, so Tick/Think avoids calling player.GetAll() each frame.


```lua
local playerData = setmetatable({}, { __mode = "k" }) -- weak keys, auto cleanup with entity GC

hook.Add("PlayerInitialSpawn", "pm_init", function(ply)
    -- numeric slots are faster than string keys on every read
    playerData[ply] = { 0, 0, 0 } -- [1]=kills, [2]=deaths, [3]=combo
end)

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

local function AddKill(ply)
    local d = playerData[ply]
    if d then d[1] = d[1] + 1 end
end

local function GetKills(ply)
    local d = playerData[ply]
    return d and d[1] or 0
end

local function Tick()
    for _, ply in ipairs(player.GetAll()) do
        local d = playerData[ply]
        if d then
            local kills = d[1]
            local deaths = d[2]
            -- use kills/deaths quickly in hot path
        end
    end
end
```
Reason: Using a dedicated weak-key table of compact numeric slots avoids per-read entity-table field dispatch (`ply.someField`) and string-key lookups, so reads/writes hit a plain Lua table cache in O(1) with lower overhead.


```lua
-- Faster for fixed collections: dense, sequential numeric table
local collection = { "red", "green", "blue" }

local sum = 0
for i = 1, #collection do
    sum = sum + #collection          -- fast indexed access in numeric loop
    print(i, collection[i])          -- O(1) array traversal
end

-- Slower alternative when iterating the same fixed data:
local map = {
    red = true,
    green = true,
    blue = true,
}

for key, value in pairs(map) do
    print(key, value)                -- hash lookup + unordered traversal
end
```
Reason: For fixed collections in Garry's Mod Lua, use a dense array (sequential numeric keys) and a numeric for-loop or `ipairs`, which is the fastest/most predictable iteration shape, while string-keyed maps with `pairs` iterate hash buckets and are slower and unordered.


```lua
local setDrawColor = surface.SetDrawColor
local r, g, b, a = 255, 255, 255, 255

local function paint()
    setDrawColor(r, g, b, a) -- hot path
    -- draw calls...
end

hook.Add("HUDPaint", "FastDraw", paint)
```
Reason: `surface.SetDrawColor(r, g, b, a)` with locals is faster in hot loops because it avoids creating/reading a `Color` table each call.


```lua
local function getPlayerMoney(steamID)
    return tonumber(sql.QueryValue("SELECT money FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))) or 0
end
```
Reason: Use local SQLite via Garry's Mod `sql` for a single server because it is in-process/local-file storage and avoids MySQL’s network round-trips, making read/write latency lower in normal use.


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

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

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

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

-- hot-path use
local UpdateSomething = function()
    for _, ply in ipairs(player.GetAll()) do
        local sid = GetSteamIDCached(ply)
        -- process sid
    end
end
```
Reason: Cache once per player in a weak-keyed table and reuse the string on hot-path reads, avoiding repeated `ply:SteamID()` calls.


```lua
-- Fast path for many fragments in Garry's Mod Lua
local function join_fast(fragments)
    local n = #fragments
    local out = {}  -- array of strings

    for i = 1, n do
        out[i] = tostring(fragments[i])
    end

    return table.concat(out)
end

-- Example
local pieces = {}
for i = 1, 5000 do
    pieces[#pieces + 1] = "piece" .. i
end

local result = join_fast(pieces)
print(#result)

-- Slow approach (for comparison):
-- local s = ""
-- for i = 1, #pieces do
--     s = s .. pieces[i]
-- end
```
Reason: Repeated `..` concatenation reallocates and copies the growing string on every iteration, while `table.concat` builds an indexed buffer and joins once, which is much faster for thousands of small chunks.


```lua
-- Faster than draw.RoundedBox(0, x, y, w, h, col)
local surfaceSetColor = surface.SetDrawColor
local surfaceDrawRect = surface.DrawRect

hook.Add("HUDPaint", "PerfRectBatch", function()
    for _, rect in ipairs(rects) do
        local c = rect.color
        surfaceSetColor(c.r, c.g, c.b, c.a)
        surfaceDrawRect(rect.x, rect.y, rect.w, rect.h)
    end
end)
```
Reason: `surface.DrawRect` calls the low-level filled-rect path directly, while `draw.RoundedBox` incurs extra wrapper/rounded-shape handling even when radius is zero.


```lua
local FONT = "DermaLarge"
local TXT_X, TXT_Y = 16, 16
local TXT_COLOR = Color(255, 255, 255, 255)

local SurfaceSetFont = surface.SetFont
local SurfaceSetTextColor = surface.SetTextColor
local SurfaceSetTextPos = surface.SetTextPos
local SurfaceDrawText = surface.DrawText

hook.Add("HUDPaint", "FastSingleLineText", function()
    local txt = ("FPS: %.0f"):format(1 / FrameTime())

    SurfaceSetFont(FONT)
    SurfaceSetTextColor(TXT_COLOR.r, TXT_COLOR.g, TXT_COLOR.b, TXT_COLOR.a)
    SurfaceSetTextPos(TXT_X, TXT_Y)
    SurfaceDrawText(txt)
end)
```
Reason: Use `surface.SetFont/SetTextColor/SetTextPos/DrawText` because it is the lightest path for one-line text and avoids `draw.DrawText`/`SimpleTextOutlined` wrapper alignment and outline overhead each frame.


```lua
local count = #myArray
```
Reason: For sequential (contiguous) array-like tables in Garry's Mod Lua, the preferred way is the Lua length operator `#`, which returns the array size for sequence-style tables.


```lua
-- Fastest choice when you just need to discard and reuse the variable:

local t = {}       -- allocate once
-- ... fill/use t a lot ...

t = {}            -- discard old contents and get a fresh table quickly
```
Reason: In Garry's Mod Lua, `t = {}` is usually faster for frequent full clears because it is effectively O(1), while `table.Empty(t)` must iterate through and nil out entries (O(n)); use `table.Empty` only when you must keep the same table reference (metatable/other refs).


```lua
local function ToSet(list)
    local set = {}
    for _, value in ipairs(list) do
        set[value] = true
    end
    return set
end

local playersBySteamID = ToSet({"STEAM_0:1:111111", "STEAM_0:1:222222", "STEAM_0:1:333333"})

-- Faster membership check on repeated queries
if playersBySteamID[ply:SteamID()] then
    print("player is in set")
end

-- Old style (slower): table.HasValue(playersList, ply:SteamID())
```
Reason: table.HasValue scans the list every call (O(n)), while a prebuilt set uses direct key lookup (O(1)) per check.


```lua
local plyData = {
    id = player:UserID(),
    name = player:Nick(),
    team = player:Team(),
    health = player:Health(),
}
```
Reason: Table constructors initialize all known keys during allocation, which is usually faster and cleaner than creating an empty table and then assigning `table.key = ...` repeatedly.


```lua
local rand = math.random

local function RandomFromSequential(t)
    local n = #t
    if n == 0 then return nil end
    return t[rand(1, n)]
end
```
Reason: For dense, 1-based sequential arrays, direct length lookup + index math avoids `table.Random` extra scanning/hash handling, giving one random call and one array access.


```lua
local x = 3.5
for i = 1, 1000000 do
    local sq = x * x
    -- use sq
end
```
Reason: In Lua (including Garry's Mod), multiplication `x * x` is the fastest way to square a number in a tight loop, while `math.pow(x, 2)` adds function-call overhead.


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


```lua
for ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- handle prop_physics entity
    end
end
```
Reason: `ents.Iterator()` streams entities directly, so you avoid creating a full entity table first.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```
Reason: `hook.Add` registers a callback for `Think`, and the string `MyAddon.Think` is the unique identifier used to track that hook entry.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: Use `IsValid(ent)` in Garry's Mod to ensure the entity handle is still alive and valid before calling any entity methods.


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

net.Receive("MyAddon.Sync", function(len, ply)
    local payload = net.ReadString()
    print("Received sync payload:", payload)
end)
```
Reason: Register the message ID on the server with `util.AddNetworkString`, then bind the same name with `net.Receive` so clients/servers can handle incoming `MyAddon.Sync` traffic.


```lua
-- One-off cache of a zero angle
a0 = Angle(0, 0, 0)

-- Reusable helper: no Angle() allocations
local function zeroAngle(a)
	a.p = 0
	a.y = 0
	a.r = 0
	return a
end

for i = 1, 1000000 do
	local ang = zeroAngle(a0) -- reused object in hot loop
	-- use ang immediately
	entity:SetAngles(ang)
end
```
Reason: Reusing one preallocated Angle and resetting its fields avoids creating thousands of temporary Angle objects (and GC pressure) versus calling Angle() every time in a hot path.


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

function GetAddonColor()
    return addonColor
end
```
Reason: For frequent reads, a flat local variable is faster than resolving `myaddon.config.color` each time because locals are direct upvalue access, while nested/global table lookups require extra table/hash traversal each call.


```lua
-- Avoid: ply:GetNWString("job")
local jobName = team.GetName(ply:Team())
```
Reason: Use the canonical player job source `ply:Team()` + `team.GetName` so you read the actual team assignment instead of a manually maintained NW string that can desync or disappear.


```lua
local p1 = Vector(10, 5, 0)
local p2 = Vector(60, 5, 0)
local threshold = 50 -- units

if p1:DistToSqr(p2) <= threshold * threshold then
    print("within threshold")
end
```
Reason: Use `DistToSqr` for squared-distance comparison so you avoid computing the expensive square root from `DistToSqr` -> real distance check.


```lua
-- Visit every entity, using the efficient iterator when it exists.
local iterate = ents.Iterator

if iterate then
    for ent in iterate() do
        if IsValid(ent) then
            -- handle ent
        end
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        if IsValid(ent) then
            -- handle ent
        end
    end
end
```
Reason: `ents.Iterator()` is the wiki-recommended, allocation-light way to traverse entities, with a safe `ents.GetAll()` fallback for environments where the iterator is unavailable.


```lua
-- Server-side: cheap nearby entity lookup around a player
local function GetEntitiesNearPlayer(ply, radius)
    local center = ply:GetPos()
    local rvec = Vector(radius, radius, radius)
    local candidates = ents.FindInBox(center - rvec, center + rvec)

    local result = {}
    local radiusSq = radius * radius
    for _, ent in ipairs(candidates) do
        if ent ~= ply and IsValid(ent) and ent:GetPos():DistToSqr(center) <= radiusSq then
            result[#result + 1] = ent
        end
    end

    return result
end

local near = GetEntitiesNearPlayer(player.GetAll()[1], 256)
```
Reason: `ents.FindInBox` is commonly a faster broad-phase spatial query than PVS for nearby scans, and the squared-distance prune restores exact radius filtering with low extra cost.


```lua
local function GetPlayersInRadius(centerPos, radius)
    local radius2 = radius * radius
    local players = player.GetAll() -- only players, no broad entity scan
    local inRange = {}

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:Alive() then
            if ply:GetPos():DistToSqr(centerPos) <= radius2 then
                inRange[#inRange + 1] = ply
            end
        end
    end

    return inRange
end

local nearby = GetPlayersInRadius(Vector(0, 0, 0), 512)
```
Reason: Iterating `player.GetAll()` does only player entities and uses `DistToSqr` (no sqrt), so you avoid `ents.FindInSphere` scanning/filtering all entity types and reduce both query and post-filter overhead.


```lua
for i = 1, n do
    -- tight loop body
end
```
Reason: The numeric `for` loop is generally faster in Garry's Mod Lua because it is implemented as a dedicated loop construct with bounded index handling and one increment/check path, while `while` adds manual increment and branch logic each iteration.


```lua
-- Faster pattern: one hook dispatch with all players in one frame.
local function DispatchPlayerTick()
    local players = player.GetHumans()
    hook.Run("MyAddon_PlayerTickAll", players, CurTime())
end

hook.Add("Tick", "MyAddon_DispatchPlayerTickAll", DispatchPlayerTick)

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

--[[]]
-- Slower pattern (per-player dispatch):
-- for i = 1, #players do
--     hook.Run("MyAddon_PlayerTickOne", players[i], CurTime())
-- end
--[[]]
```
Reason: dispatching once per tick moves hook overhead to a single call and does one explicit player loop, which is cheaper than invoking `hook.Run` for every player each tick (O(1) hook dispatches vs O(N) dispatches).


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

    local hp = ply:Health()

    surface.SetDrawColor(0, 180, 0, 180)
    surface.DrawRect(16, 16, hp, 16)

    surface.SetDrawColor(0, 0, 0, 255)
    surface.DrawOutlinedRect(16, 16, 100, 16)

    draw.SimpleText("HP: " .. hp, "DermaDefault", 20, 38, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```
Reason: Cache `LocalPlayer()` and `Health()` in locals so the three draw operations reuse one value and avoid repeated cross-boundary player health fetches in the same frame.


```lua
local WHITE = color_white -- or: Color(255, 255, 255, 255)

hook.Add("HUDPaint", "MyPaintLoop", function()
    surface.SetDrawColor(WHITE)

    for i = 1, 200 do
        surface.DrawRect(10, i * 12, 120, 8)
    end
end)
```
Reason: Precompute the white color once and set it once per paint call so the loop does not allocate a new `Color` object every iteration.


```lua
local sin = math.sin  -- bind function once, outside hot loop

local sum = 0
for i = 1, 1000000 do
    local x = i * 0.01
    sum = sum + sin(x) -- fast local call
end
```
Reason: `math.sin` is looked up once instead of on every loop iteration, replacing repeated global/table access with a fast local.


```lua
local localPlayer = nil

local function UpdateLocalPlayer()
    local p = LocalPlayer()
    if IsValid(p) then
        localPlayer = p
    end
end

hook.Add("Initialize", "cache_local_player", UpdateLocalPlayer)
hook.Add("Think", "refresh_local_player", function()
    if not IsValid(localPlayer) then
        UpdateLocalPlayer()
    end
end)

local function OnRender()
    local lp = localPlayer
    if not IsValid(lp) then return end

    local hp = lp:Health()
    local pos = lp:GetPos()
    -- use hp/pos here
end
hook.Add("HUDPaint", "use_cached_local_player", OnRender)
```
Reason: Cache `LocalPlayer()` once into a local variable and only refresh it when invalid (during init/think), so high-frequency code reads `localPlayer` instead of calling `LocalPlayer()` every time.


```lua
local LOOK_COS = math.cos(math.rad(45)) -- ~45° tolerance
local LOOK_COS2 = LOOK_COS * LOOK_COS
local MAX_DIST2 = 1024 * 1024

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

    local toB = p2:EyePos() - p1:EyePos()
    local dist2 = toB:LengthSqr()
    if dist2 < 1e-6 or dist2 > MAX_DIST2 then return false end

    local a1 = p1:GetAimVector() -- unit vector
    local a2 = p2:GetAimVector() -- unit vector

    local dot1 = a1:Dot(toB)   -- equals |toB| * cos(angle1)
    local dot2 = a2:Dot(-toB)  -- equals |toB| * cos(angle2)

    if dot1 <= 0 or dot2 <= 0 then return false end
    return dot1 * dot1 >= LOOK_COS2 * dist2 and dot2 * dot2 >= LOOK_COS2 * dist2
end
```
Reason: Compare dot products against squared cosine threshold with one vector difference and LengthSqr, so no `math.acos`, no angle objects, and no square-rooted trig path.


```lua
SomeHelper(ply)
```
Reason: In Lua (including Garry's Mod Lua), `ply:SomeHelper()` is just syntactic sugar for `SomeHelper(ply)`-style method invocation, so runtime cost is effectively the same; the difference is mostly API readability, not performance.


```lua
-- Hot-path debug in Garry's Mod Lua: faster than print
local DBG_PREFIX = "[DBG] "

local function debugLine(msg)
    if not DBG then return end
    Msg(DBG_PREFIX .. msg .. "\n")
end

hook.Add("Think", "PerfDebug", function()
    debugLine("entities=" .. #ents.GetAll())
end)
```
Reason: `Msg` is a lower-level console writer and avoids `print`’s vararg/tab/newline formatting overhead, so it’s the usual hot-path replacement when you need minimal debug output cost.


```lua
local nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

local sum = 0
local n = #nums
for i = 1, n do
    sum = sum + nums[i]
end
```

Reason: Use a numeric `for` loop (`for i = 1, n`) because it is the lowest-overhead path for dense, 1-based array-like tables: direct integer indexing with a cached bound, while `ipairs` adds iterator overhead and `pairs` is slower and unordered for arrays.


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

    for i = 1, #players do
        local ply = players[i]
        local money = ply:getDarkRPVar("money")

        if ply:IsPlayer() and ply:Alive() and money and money >= minMoney then
            outN = outN + 1
            out[outN] = string.lower(ply:Nick())
        end
    end

    return out
end

local names = GetRichAliveNames(player.GetAll(), 1000)
```
Reason: This uses one tight `for` loop to perform filter + map together, avoiding fn-style chained closures and intermediate tables/calls that add allocation and dispatch overhead in Garry's Mod Lua.


```lua
local cachedPlayers = {}
local seen = {}

local function cacheAdd(ply)
    if not IsValid(ply) or seen[ply] then
        return
    end

    seen[ply] = true
    cachedPlayers[#cachedPlayers + 1] = ply
end

local function cacheRemove(ply)
    if not seen[ply] then
        return
    end

    seen[ply] = nil

    for i = #cachedPlayers, 1, -1 do
        if cachedPlayers[i] == ply then
            cachedPlayers[i] = cachedPlayers[#cachedPlayers]
            cachedPlayers[#cachedPlayers] = nil
            break
        end
    end
end

for _, ply in ipairs(player.GetAll()) do
    cacheAdd(ply)
end

hook.Add("PlayerInitialSpawn", "CachePlayers_Add", cacheAdd)
hook.Add("PlayerDisconnected", "CachePlayers_Remove", cacheRemove)

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

        if IsValid(ply) then
            -- heavy per-tick work goes here
        end
    end
end)
```
Reason: The player list is maintained in hooks (`PlayerInitialSpawn` and `PlayerDisconnected`) so it updates only when players join/leave, avoiding `player.GetAll()` inside every tick.


```lua
-- Faster per-player cache for hot reads
local playerState = {}

local function stateOf(ply)
    return playerState[ply:EntIndex()]
end

hook.Add("PlayerInitialSpawn", "perf.playerstate.init", function(ply)
    playerState[ply:EntIndex()] = {
        lastShot = 0,
        combo = 0,
        cooldown = 0,
    }
end)

hook.Add("PlayerDisconnected", "perf.playerstate.cleanup", function(ply)
    playerState[ply:EntIndex()] = nil
end)

local function canShoot(ply)
    local st = stateOf(ply)
    if not st then return false end

    return CurTime() > st.cooldown
end

local function onShoot(ply)
    local st = stateOf(ply)
    st.combo = st.combo + 1
    st.lastShot = CurTime()
    st.cooldown = CurTime() + 0.08
end
```
Reason: Using a dedicated numeric-keyed state table (`EntIndex` -> record) avoids repeated `ply.someField` lookups on entity userdata, gives faster predictable table reads in hot loops, and makes cleanup explicit on disconnect.


```lua
-- Fast shape for frequent iteration: contiguous integer-keyed array
local weapons = { "pistol", "shotgun", "rifle", "grenade" }

local total = 0
for i = 1, #weapons do
    local w = weapons[i]
    total = total + 1
    print(i, w)
end

-- Reference slower shape: string-keyed map
local weaponMap = {
    pistol = true,
    shotgun = true,
    rifle = true,
    grenade = true,
}

for name, enabled in pairs(weaponMap) do
    print(name, enabled)
end
```
Reason: Use a sequential number-indexed table and iterate with `for i = 1, #t` (or `ipairs`) for fixed collections in Garry's Mod Lua, because it stays in the array fast-path, while string-keyed maps use hash lookup order and slower `pairs` traversal.


```lua
-- Faster in hot paths: pass primitives, not a Color table
local r, g, b, a = 255, 80, 20, 255

hook.Add("HUDPaint", "FastDrawPath", function()
    for i = 1, 200 do
        surface.SetDrawColor(r, g, b, a) -- numeric args
        surface.DrawRect(12, i * 4, 160, 3)
    end
end)
```
Reason: In tight drawing loops, numeric args avoid creating/reading a Color object each call, so `SetDrawColor` is cheaper and stays allocation-free.


```lua
local hp = sql.QueryValue("SELECT hp FROM player_stats WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: For a single GMod server with no cross-server sync, local SQLite via `sql.Query`/`sql.QueryValue` is usually lower latency because reads/writes stay on disk locally, while MySQL adds network and external server overhead even on LAN.


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

local playerMeta = FindMetaTable("Player")
function playerMeta:GetSteamIDCached()
    local sid = steamIDCache[self]
    if sid ~= nil then
        return sid
    end

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

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

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

-- hot path
local sid = ply:GetSteamIDCached()
```
Reason: Cache per-player SteamID once (primed on spawn and invalidated on disconnect), so hot-path calls become cheap table lookups instead of repeated method calls.


```lua
local chunks = {}
for i = 1, 5000 do
    chunks[#chunks + 1] = "chunk_" .. i .. "\n"
end

local function with_concat_operator(t)
    local out = ""
    for i = 1, #t do
        out = out .. t[i]
    end
    return out
end

local function with_table_concat(t)
    return table.concat(t, "")
end

local a = with_concat_operator(chunks)
local b = with_table_concat(chunks)
print(#a, #b, a == b)
```
Reason: Use `table.concat` (or another buffer pattern) for one-pass join so the final string is built once instead of reallocating a larger string on every `..` step.


```lua
-- Fast replacement for: draw.RoundedBox(0, x, y, w, h, col)
-- inside your per-frame draw loop
surface.SetDrawColor(255, 128, 0, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is a lower-level fill-rect call than `draw.RoundedBox`, so with radius 0 it avoids the extra rounded-rect path/branching overhead while still drawing solid rectangles.


```lua
-- Fastest for per-frame single-line HUD text: direct surface.* path.
-- Use DrawText only; skip draw.DrawText and SimpleTextOutlined wrappers.
surface.CreateFont("PerfHUDSmall", {
    font = "Trebuchet24",
    size = 24,
    weight = 500,
    antialias = true
})

local textFont = "PerfHUDSmall"
local x, y = 16, 16
local r, g, b, a = 255, 255, 255, 255

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

    surface.SetFont(textFont)      -- minimal state setup
    surface.SetTextColor(r, g, b, a) -- numeric args avoid per-frame Color() alloc
    surface.SetTextPos(x, y)
    surface.DrawText(s)
end)
```
Reason: `surface.SetFont + SetTextPos + DrawText` is the leanest text path and avoids the extra alignment, shadow, and outline work done by `draw.DrawText` / `SimpleTextOutlined` for single-line per-frame rendering.


```lua
local arr = { "a", "b", "c" }
local n = #arr
```
Reason: Use the Lua length operator `#` for sequential (array-like) tables; it is O(1) and returns the array length, which is the preferred approach in Garry's Mod Lua.


```lua
-- Fastest way to discard a large sequential table in a hot loop:
-- rebinding to a new table is O(1).
t = {}
```
Reason: `t = {}` is generally faster than `table.Empty(t)` because it just creates a new table reference, while `table.Empty` iterates through all existing entries and clears them one by one (O(n)).


```lua
local allowed = {
    ["admin"] = true,
    ["moderator"] = true,
    ["owner"] = true,
}

local function IsAllowed(role)
    return allowed[role] ~= nil -- true when role exists in the set
end

if IsAllowed(ply:GetUserGroup()) then
    -- fast path
end
```
Reason: `table.HasValue` scans the whole array every call (O(n)), while keyed-set lookups are direct hash lookups (O(1) average), so repeated membership checks are much faster.


```lua
local ent = {
    class = "npc_antlion",
    health = 100,
    speed = 250
}
```
Reason: In Garry's Mod Lua, constructor syntax is faster for known fields because the table and its keys are created in one allocation+init pass, while assigning after `{}` does extra per-field writes.


```lua
local function RandomFromSequential(t)
    local n = #t
    if n == 0 then return nil end
    return t[math.random(n)]
end
```
Reason: `table.Random` is general-purpose and does extra checks/iteration for hash-style tables, while direct indexed lookup uses one `#t` and one `math.random` lookup for contiguous arrays (O(1) per pick).


```lua
for i = 1, n do
    local x = values[i]
    local sx = x * x
end
```
Reason: Use `x * x` because it is direct numeric multiplication with minimal overhead, unlike `math.pow`, which is slower in tight loops due to a function call.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- do something with ply
end
```
Reason: `player.GetAll()` returns the connected players list, and `ipairs` walks every entry once.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process ent
end
```
Reason: `ents.FindByClass("prop_physics")` returns only matching entities, so you iterate them directly without first collecting every map entity into a table.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- minimal callback
end)
```
Reason: `hook.Add` registers the Think hook callback under the unique identifier `MyAddon.Think`, so it will run every frame.


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: `IsValid` is the Garry's Mod-safe check that returns false for `nil` or removed/invalid entities, so only call methods inside that guard.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local payload = net.ReadString()
    -- handle incoming sync payload
end)
```
Reason: `net.Receive("MyAddon.Sync", ...)` is the Garry's Mod registration call that binds a callback to the incoming network message of that exact name.


```lua
local zeroAnglePool = {}
local zeroAngleCursor = 0

local function BeginHotBatch()
    zeroAngleCursor = 0 -- call once per frame/update before the hot loop
end

local function FreshZeroAngle()
    zeroAngleCursor = zeroAngleCursor + 1
    local ang = zeroAnglePool[zeroAngleCursor]
    if not ang then
        ang = Angle() -- allocate once per slot
        zeroAnglePool[zeroAngleCursor] = ang
    end
    ang.p, ang.y, ang.r = 0, 0, 0
    return ang
end

BeginHotBatch()
for i = 1, 128 do
    local ang = FreshZeroAngle()
    -- use ang here
end
```
Reason: Reusing pooled `Angle` objects and zeroing fields (`p`,`y`,`r`) removes per-iteration `Angle()` allocations and cuts GC pressure in the hot path.


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

local c = addonColor
```
Reason: Use a cached flat `local` variable because locals are register-accessed, while `myaddon.config.color` does repeated table-key lookups and globals are slower than locals.


```lua
local jobName = team.GetName(ply:Team()) -- preferred over ply:GetNWString("job")
```
Reason: `team.GetName(ply:Team())` is the canonical DarkRP/GMod job lookup, while `GetNWString("job")` reads a legacy NW variable that can become stale or absent.


```lua
if pos1:DistToSqr(pos2) < maxDist * maxDist then
    -- within range without computing actual distance
end
```
Reason: Use `DistToSqr` in Garry's Mod Lua to compare squared distances directly and avoid the expensive square-root from `Distance` when only a threshold check is needed.


```lua
for ent in ents.Iterator() do
    if IsValid(ent) then
        -- Visit each valid entity here.
        print(ent:GetClass())
    end
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient entity iterator in Garry's Mod since it streams entities without building a temporary table like `ents.GetAll()`. `IsValid(ent)` ensures only live entities are processed.


```lua
local function FindNearbyEntities(ply, radius)
    local origin = ply:GetPos()
    local r = radius

    local mins = origin - Vector(r, r, r)
    local maxs = origin + Vector(r, r, r)

    local nearby = {}
    local i = 0
    local r2 = r * r

    for _, ent in ipairs(ents.FindInBox(mins, maxs)) do
        if IsValid(ent) and ent ~= ply and ent:GetPos():DistToSqr(origin) <= r2 then
            i = i + 1
            nearby[i] = ent
        end
    end

    return nearby
end
```
Reason: `ents.FindInBox` is a common benchmark-faster built-in for cheap area lookups on servers, using a coarse AABB pass with an optional squared-distance filter to keep the exact radius check inexpensive.


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSq = radius * radius
    local players = player.GetHumans() -- use player.GetAll() if you want bots included
    local result = {}

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

        if IsValid(ply) and not ply:IsDormant() and ply:GetPos():DistToSqr(pos) <= radiusSq then
            result[#result + 1] = ply
        end
    end

    return result
end
```
Reason: Iterate only player entities with `player.GetHumans()` (or `player.GetAll()`), then use a precomputed squared-radius `DistToSqr` check, which is cheaper than scanning all entities via `ents.FindInSphere` and avoids per-entity spatial query overhead + unnecessary sqrt work.


```lua
local sum = 0
for i = 1, n do
    sum = sum + i
end
```
Reason: In Garry's Mod Lua (Lua/LuaJIT), a numeric `for` loop is generally faster because it is a built-in counted loop with tighter bytecode/JIT path, while `while` adds explicit increment and comparison overhead each iteration.


```lua
-- Faster: one hook dispatch for the whole tick
hook.Add("Think", "MyTickDispatcher", function()
    local players = player.GetAll()
    if #players == 0 then return end

    -- one dispatch, one call path
    hook.Run("MyPlayerBatchTick", players, FrameTime())
end)

hook.Add("MyPlayerBatchTick", "MyPlayerBatchHandler", function(players, dt)
    for i = 1, #players do
        local ply = players[i]
        if not IsValid(ply) then continue end

        -- custom per-player logic
        if ply:Alive() then
            ply:SetArmor(math.min(ply:Armor() + 1, 100))
        end
    end
end)

-- Slower version (avoid):
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("MyPlayerTick", ply, FrameTime())
-- end
```
Reason: One hook.Run per tick avoids dispatch overhead N times per frame by batching all players into one call, then doing one internal loop over players in the handler.


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

    local health = ply:Health()
    local maxHealth = ply:GetMaxHealth()
    local healthRatio = health / math.max(maxHealth, 1)

    local x, y, w, h = 20, 20, 220, 18

    draw.RoundedBox(0, x, y, w, h, Color(0, 0, 0, 180))
    draw.RoundedBox(0, x, y, w * healthRatio, h, Color(120, 220, 120, 220))
    draw.SimpleText("HP: " .. health, "DermaDefault", x + 6, y + h * 0.5, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end)
```
Reason: Cache `LocalPlayer()` and `Health()` once per frame, then reuse the `health` value for every draw path to avoid repeated expensive calls inside HUDPaint.


```lua
-- Cache once, reuse in every paint call
local WHITE = color_white
local setColor = surface.SetDrawColor
local drawRect = surface.DrawRect

hook.Add("HUDPaint", "FastPaint", function()
    setColor(WHITE) -- set once, not per-iteration

    for i = 1, 256 do
        local x = i * 6
        local y = 24
        drawRect(x, y, 4, 4)
    end
end)
```
Reason: Cache the color once (or use `color_white`) and avoid `Color(255,255,255)` inside the loop so you eliminate repeated allocations and per-iteration color setup overhead.


```lua
local sin = math.sin -- cache lookup outside hot loop

for i = 1, 100000 do
    local y = sin(i * 0.01)
    -- use y
end
```
Reason: `sin` is read once as a local, so each iteration avoids repeated `math` table and field lookups of `math.sin` in a tight loop.


```lua
local localPlayer

-- Cache LocalPlayer() and only refresh when invalidated by engine state changes.
local function GetLocalPlayer()
    local lp = localPlayer

    if not IsValid(lp) then
        lp = LocalPlayer()
        localPlayer = lp
    end

    return lp
end

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

local function DoHudStuff()
    local lp = GetLocalPlayer()
    if not IsValid(lp) then return end

    -- use lp every frame instead of calling LocalPlayer() repeatedly
end
```
Reason: Cache the local player once in a local variable and refresh only when invalid so repeated calls reuse the same object without repeated global lookups.


```lua
local LOOK_ANGLE_DEG = 25
local COS_LIMIT = math.cos(math.rad(LOOK_ANGLE_DEG))
local COS_LIMIT_SQ = COS_LIMIT * COS_LIMIT

local function RoughlyFacingEachOther(p1, p2, maxDistance)
    local p1Pos, p2Pos = p1:EyePos(), p2:EyePos()
    local dx, dy, dz = p2Pos.x - p1Pos.x, p2Pos.y - p1Pos.y, p2Pos.z - p1Pos.z

    local distSq = dx * dx + dy * dy + dz * dz
    if maxDistance and distSq > maxDistance * maxDistance then return false end

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

    local dot1 = a1.x * dx + a1.y * dy + a1.z * dz      -- p1 looking toward p2
    if dot1 <= 0 then return false end
    if dot1 * dot1 < COS_LIMIT_SQ * distSq then return false end

    local dot2 = - (a2.x * dx + a2.y * dy + a2.z * dz) -- p2 looking toward p1
    if dot2 <= 0 then return false end

    return dot2 * dot2 >= COS_LIMIT_SQ * distSq
end
```
Reason: Using the dot product against eye-to-eye displacement and comparing against `cos²(θ)` checks forward-facing FOV on both players in constant time and skips `math.acos`/angle math entirely for a much cheaper check.


```lua
ply:SomeHelper()
```
Reason: In Garry's Mod Lua, `ply:SomeHelper()` compiles to the same call shape as `SomeHelper(ply)`, so there is no meaningful performance difference; use `:` when it is a method-style helper on `ply`.


```lua
local dbg = MsgN -- cache globally scoped lookup once
dbg("[DBG] hp=" .. tostring(ent:Health()) .. " ammo=" .. tostring(ent:GetAmmoCount()))
```
Reason: `MsgN` writes straight to the GMod console and avoids `print`’s slower variadic formatting path (and with a cached local reference it’s the cheaper hot-path alternative.


```lua
local nums = {10, 20, 30, --[[...]] }
local n = #nums

for i = 1, n do
    local v = nums[i]
    -- use v
end
```
Reason: Use the numeric `for` loop (`for i = 1, #nums`) for dense array-like tables because it does direct index access with no iterator callback/state overhead, making it the fastest practical choice in Garry's Mod Lua.


```lua
local function collectRichCitizenNames(minMoney)
    local players = player.GetAll()
    local out = {}
    local n = 0

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

    return out
end

local richCitizens = collectRichCitizenNames(10000)
```
Reason: This is faster than fn-style chains because it does filter and map in one linear pass with direct table writes, avoiding closure chaining, iterator overhead, and intermediate tables per stage.


```lua
local cachedPlayers = {}
local inCache = {}

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

    for _, ply in ipairs(player.GetAll()) do
        local i = ply:EntIndex()
        inCache[i] = true
        cachedPlayers[#cachedPlayers + 1] = ply
    end
end

local function addPlayer(ply)
    local i = ply:EntIndex()
    if inCache[i] then return end

    inCache[i] = true
    cachedPlayers[#cachedPlayers + 1] = ply
end

local function removePlayer(ply)
    local i = ply:EntIndex()
    if not inCache[i] then return end

    inCache[i] = nil

    for n = #cachedPlayers, 1, -1 do
        if cachedPlayers[n] == ply then
            cachedPlayers[n] = cachedPlayers[#cachedPlayers]
            cachedPlayers[#cachedPlayers] = nil
            break
        end
    end
end

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

hook.Add("Think", "PlayerCache_Think", function()
    for _, ply in ipairs(cachedPlayers) do
        -- fast per-tick logic using cachedPlayers
    end
end)
```
Reason: This removes per-tick `player.GetAll()` allocation and lookup work by updating a cached player array only on join/leave hooks, then iterating that cache in Think.


```lua
local plyState = {} -- [ply EntIndex] = table of hot temp values

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

function SetTempValue(ply, value)
    getState(ply).tmp = value
end

function GetTempValue(ply)
    local s = plyState[ply:EntIndex()]
    if s then return s.tmp end
    return nil
end

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

local function Think()
    for _, ply in ipairs(player.GetAll()) do
        local s = plyState[ply:EntIndex()]
        if s then
            local v = s.tmp
            -- use v
        end
    end
end
```
Reason: Use a local Lua table keyed by EntIndex with lazy per-player subtables so hot reads are plain table lookups (`plyState[idx]`) instead of userdata field access on `ply` objects.


```lua
-- Faster: dense array-style table for fixed collections
type = { "idle", "walk", "run", "jump" }

for i = 1, #type do
    local state = type[i]
    print(state)
end

-- Slower/less cache-friendly for iteration:
-- stateMap = { idle = 1, walk = 2, run = 3, jump = 4 }
```
Reason: Use a sequential number-indexed table (array) and index/count-based loop in Lua because it uses dense array storage, predictable order, and lower iteration overhead than hash-map key iteration with string keys.


```lua
-- Hot draw path: keep a plain color in locals, pass numeric channels.
local SetDrawColor = surface.SetDrawColor
local DrawRect = surface.DrawRect

local r, g, b, a = 255, 128, 32, 255

hook.Add("HUDPaint", "FastPathDraw", function()
    SetDrawColor(r, g, b, a)
    DrawRect(10, 10, 64, 64)
end)
```
Reason: Passing `r, g, b, a` directly avoids creating/reading a `Color` object on each hot-path call, which is the lower-overhead path.


```lua
local steamid = "STEAM_0:1:12345"
local playtime = sql.QueryValue("SELECT playtime FROM player_data WHERE steamid = " .. sql.SQLStr(steamid) .. ";")

if playtime then
    print("playtime:", playtime)
end
```
Reason: For a single Garry's Mod server with no cross-server sync, local SQLite (`sql`) is usually lower latency because reads/writes stay in-process and avoid network round-trips and client/server overhead that remote MySQL adds.


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

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

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

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

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

-- hot path
local sid = GetSteamIDCached(ply)
```
Reason: Store `ply:SteamID()` once per player in a weak-key cache and reuse it in hot loops, with disconnect cleanup preventing stale entries.


```lua
local function concat_many(parts)
    -- Fast pattern for GMod Lua: collect fragments, then join once.
    local chunks = {}
    for i = 1, #parts do
        chunks[i] = parts[i]
    end
    return table.concat(chunks)
end

local function concat_naive(parts)
    -- Slow pattern (O(n^2)); only for comparison.
    local s = ""
    for i = 1, #parts do
        s = s .. parts[i]
    end
    return s
end

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

local fast = concat_many(parts)
-- local slow = concat_naive(parts)
```
Reason: `table.concat` is faster for many fragments in Garry's Mod Lua because it joins once in one internal pass, while repeated `..` creates a new string on every loop iteration, causing repeated reallocations and quadratic work.


```lua
-- faster than draw.RoundedBox(0, x, y, w, h, col)
surface.SetDrawColor(255, 128, 0, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox` always routes through rounding code and validation even at radius 0, while `surface.SetDrawColor` + `surface.DrawRect` skips rounded-corner path and does the plain rect primitive draw.


```lua
local TEXT = "FPS: " .. tostring(math.floor(FrameTime() * 1000 + 0.5))

surface.CreateFont("PerfHUD", {
    font = "Arial",
    size = 20,
    weight = 500,
    antialias = true,
})

hook.Add("HUDPaint", "PerfHUD_DrawSingleLine", function()
    surface.SetFont("PerfHUD")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(16, 16)
    surface.DrawText(TEXT)
end)
```
Reason: Use `surface.*` text primitives (`SetFont` + `SetTextColor` + `SetTextPos` + `DrawText`) to avoid the extra wrapper/outline overhead of `draw.DrawText` and especially `SimpleTextOutlined`, which is cheaper for a single-line per-frame HUD draw.


```lua
local n = #arr
```
Reason: In Garry's Mod Lua, `#` is the preferred length operator for sequential, contiguous array-like tables.


```lua
-- Fastest way to discard contents when you can rebind the variable:
local t = {1, 2, 3, 4, 5}

t = {}

-- table.Empty(t) is needed only if other code must keep the same table reference.
```
Reason: `t = {}` is generally faster for repeated clears because it allocates a fresh table in O(1) time, while `table.Empty(t)` must iterate and nil each entry in O(n); use `table.Empty` only when table identity must be preserved.


```lua
local function toSet(list)
    local set = {}
    for i = 1, #list do
        set[list[i]] = true
    end
    return set
end

local weapons = toSet({"weapon_crowbar", "weapon_pistol", "weapon_ar2", "weapon_shotgun"})

local class = "weapon_pistol"
if weapons[class] then
    print("weapon is allowed")
end

-- Example of old way (slower):
-- table.HasValue({"weapon_crowbar", "weapon_pistol", "weapon_ar2", "weapon_shotgun"}, class)
```
Reason: `table.HasValue` on an array checks every element each call, while a map-style set uses direct key lookup so membership is constant-time on average (`O(1)`).


```lua
-- Faster: define known fields directly in constructor
local function make_tbl()
    return { hp = 100, armor = 50, name = "player", alive = true }
end

-- Baseline for reference
local function make_tbl_late()
    local t = {}
    t.hp = 100
    t.armor = 50
    t.name = "player"
    t.alive = true
    return t
end

local rounds = 200000
local t0 = SysTime()
for i = 1, rounds do make_tbl() end
local t1 = SysTime()
for i = 1, rounds do make_tbl_late() end
local t2 = SysTime()
print("constructor:", t1 - t0, "late:", t2 - t1)
```
Reason: Use the constructor form (`{ key = value, ... }`), since it initializes the table in one step and is typically faster than creating `{}` then assigning fields.


```lua
-- Faster random element picker for a sequential (array-like) table
local function randomElement(arr)
    local n = #arr
    if n == 0 then return nil end
    return arr[math.random(n)]
end

-- Example
local weapon = randomElement({"pistol", "smg", "shotgun", "rifle"})
```
Reason: Sequential tables allow direct indexed access in O(1), so `#arr` + `arr[math.random(n)]` is faster than `table.Random`, which must do extra logic for arbitrary key tables.


```lua
local sum = 0
for i = 1, #values do
    local x = values[i]
    sum = sum + x * x
end
```
Reason: Use `x * x`; multiplication is the direct arithmetic path and avoids per-iteration `math.pow(x, 2)` function-call overhead.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- handle each connected player
end
```
Reason: `player.GetAll()` returns all currently connected players, and `ipairs` iterates through that list directly for each player entity.