```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one by one, so it avoids allocating a full table like `ents.GetAll()` or `ents.FindByClass()` first.


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


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that the entity reference still exists and is safe to call methods on.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` registers a callback for the named incoming net message, and the handler receives the message length and the sending player on the server.


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

-- Hot path
someEntity:SetAngles(ANGLE_ZERO)
```
Reason: Reusing one shared zero `Angle` avoids repeated object construction and garbage pressure from calling `Angle()` on every hot-path iteration.


```lua
local MYADDON_COLOR = "blue"
local color = MYADDON_COLOR
```
Reason: A flat local is fastest for frequent reads because Lua resolves locals more cheaply than repeated table field lookups like `myaddon.config.color`.


```lua
local preferred = ply:getDarkRPVar("job")
local old = ply:GetNWString("job")
```
Reason: `ply:getDarkRPVar("job")` is the DarkRP-supported API for job names; `GetNWString("job")` is older, less direct, and can desync from DarkRP state.


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


```lua
for ent in ents.Iterator() do
    -- use ent
end
```
Reason: `ents.Iterator()` avoids building the table returned by `ents.GetAll()`, so it is the efficient wiki-recommended choice when you only need to visit each live entity once.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 512)
```
Reason: `ents.FindInSphere` is a common fast built-in for cheap radius-based spatial queries around a player, without relying on `FindInPVS`.


```lua
local player_GetAll = player.GetAll
local DistToSqr = FindMetaTable("Vector").DistToSqr

local function FindPlayersInRadius(pos, radius)
    local players = player_GetAll()
    local out = {}
    local radiusSqr = radius * radius
    local n = 0

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

    return out
end
```
Reason: `ents.FindInSphere` scans all entities and allocates a broader result set, while iterating `player.GetAll()` only visits players and uses squared distance to avoid the square root cost.


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


```lua
-- Faster: one hook dispatch per tick, pass the player list once.
local HOOK = "MyPerTickPlayers"

hook.Add("Tick", "NotifyCustomLogic", function()
    local players = player.GetHumans()
    hook.Run(HOOK, players)
end)

-- Slower: repeated hook dispatch inside the player loop.
-- hook.Add("Tick", "NotifyCustomLogic", function()
--     for _, ply in ipairs(player.GetHumans()) do
--         hook.Run(HOOK, ply)
--     end
-- end)
```
Reason: `hook.Run` has non-trivial dispatch overhead, so calling it once per tick and iterating players inside the listener is faster than paying that hook dispatch cost once per player.


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

draw.SimpleText(hp, "DermaLarge", x1, y1, color_white)
draw.RoundedBox(4, x2, y2, math.Clamp(hp, 0, 100) * 2, 20, color_green)
draw.SimpleText(hp .. "%", "DermaDefaultBold", x3, y3, color_white)
```
Reason: Cache `LocalPlayer():Health()` in a local once per frame so the three draw calls reuse the value instead of repeating the function call.


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

hook.Add("HUDPaint", "FastPaintExample", function()
    for i = 1, 1000 do
        surface.SetDrawColor(COLOR_WHITE)
        surface.DrawRect(i, 100, 1, 20)
    end
end)
```
Reason: Hoist the `Color` allocation out of the paint loop so the hot path reuses one object instead of creating a new color every iteration.


```lua
local sin = math.sin

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


```lua
local lp

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

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

    local pos = lp:GetPos()
    local vel = lp:GetVelocity()
    -- use lp repeatedly here instead of calling LocalPlayer() each time
end)
```
Reason: Caching the `LocalPlayer()` result in a local upvalue avoids repeated global lookup/function call overhead while still refreshing safely if the player entity is not valid yet.


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

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

    -- If their forward aim directions point opposite ways, they are facing each other.
    return aimA:Dot(aimB) <= LOOK_DOT_THRESHOLD
end
```
Reason: A dot product is much cheaper than `math.acos` and gives the same threshold test for “roughly opposite” aim directions without converting to angles.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster for a helper you control because `:` adds a method lookup/desugaring step, while a direct function call avoids that extra table access.


```lua
MsgN("hot path debug: ", value)
```
Reason: `MsgN` writes to the console with less overhead than `print`, so it is the usual faster choice for hot-path debug output in Garry's Mod Lua.


```lua
for i = 1, #t do
    local n = t[i]
    -- use n
end
```
Reason: For a large sequential numeric array, a numeric `for` avoids the extra iterator overhead of `pairs` and `ipairs` and is typically the fastest of the three.


```lua
local players = player.GetAll()
local result = {}

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

    if IsValid(ply) and ply:Alive() and ply:isCP() then
        result[#result + 1] = {
            nick = ply:Nick(),
            money = ply:getDarkRPVar("money") or 0,
        }
    end
end

return result
```
Reason: A single plain-Lua pass avoids `fn.Filter(...):Map(...)` iterator/combinator overhead, extra closures, and intermediate tables, so it is typically faster in hot DarkRP code.


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

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

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

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- hot-path work here
        end
    end
end)
```
Reason: This avoids allocating and traversing a fresh `player.GetAll()` result every tick, moving that cost to join/leave events and keeping the hot path to a tight indexed loop over a cached table.


```lua
local hpByPlayer = {}

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

local function GetTempHP(ply)
    return hpByPlayer[ply]
end

hook.Add("PlayerDisconnected", "ClearTempHP", function(ply)
    hpByPlayer[ply] = nil
end)
```
Reason: A side table keyed by `ply` avoids repeated entity table field lookups on the player object and is typically faster for hot reads of temporary data.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: A sequential number-indexed array is faster to iterate than a string-keyed map because it avoids key hashing and uses Lua's optimized array traversal path.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw RGBA numbers avoids the extra table/object handling of a `Color` value and is the faster hot-path call style.


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


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

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

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

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

-- hot path
local function HandlePlayers(players)
    for i = 1, #players do
        local ply = players[i]
        local steamId = GetSteamIDCached(ply)
        -- use steamId
    end
end
```
Reason: It avoids repeated `ply:SteamID()` calls on the hot path by memoizing once per player while using weak keys so disconnected player objects can be garbage-collected.


Answer must contain 0 through 0 candidate loops.

```lua
local parts = {}

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

local result = table.concat(parts)
```
Reason: `table.concat` avoids creating a new full string on every `..` step, so building from many pieces does less repeated copying and is faster.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the extra wrapper work in `draw.RoundedBox`, so for plain non-rounded rectangles it is slightly cheaper per frame.


```lua
local text = "Hello"
local x, y = 100, 100
local r, g, b, a = 255, 255, 255, 255

surface.SetFont("DermaDefault")

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetTextColor(r, g, b, a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetTextPos` + `surface.DrawText` is the faster single-line path because it avoids the extra alignment/wrapping work in `draw.DrawText` and the multiple outline passes in `draw.SimpleTextOutlined`.


```lua
local len = #tbl
```
Reason: `#` is the preferred built-in length operator for sequential array-like tables in Garry's Mod Lua.


```lua
local t = {}
```
Reason: `t = {}` is generally faster because it drops the old array reference in one step, while `table.Empty(t)` walks the table and removes entries one by one.


```lua
-- Slower: linear scan every lookup
local weapons = { "crowbar", "pistol", "shotgun" }
if table.HasValue(weapons, "pistol") then
    print("found")
end

-- Faster: hash set with O(1)-style lookup
local weaponSet = {
    crowbar = true,
    pistol = true,
    shotgun = true,
}

if weaponSet["pistol"] then
    print("found")
end
```
Reason: `table.HasValue` scans the whole list, while a key lookup in a set-style table avoids the linear search and is the standard faster membership check in Lua.


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

-- slower
local u = {}
u.x = 1
u.y = 2
u.z = 3
```
Reason: For a small table with known fields, the table constructor is faster because it builds the table in one step and avoids separate field assignment operations.


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


```lua
local y = x * x
```
Reason: `x * x` avoids function-call overhead and is the preferred fast form in a tight loop.


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

```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` visits currently connected players without materializing `player.GetAll()` first.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, so it avoids building a full entity table before filtering for `prop_physics`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- per-frame logic
end)
```
Reason: `hook.Add` registers a callback on Garry's Mod's `Think` hook using `MyAddon.Think` as the unique identifier.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: In Garry's Mod, `IsValid(ent)` is the standard guard because it returns false for `nil`, invalid, or removed entities, so method calls on `ent` are only made when the reference is still safe to use.


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


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

-- hot path
ent:SetAngles(ZERO_ANGLE)
```
Reason: Reusing one shared zeroed `Angle` avoids allocating and initializing a new userdata/table on every call, which is faster in hot paths.


```lua
local MYADDON_COLOR = Color(255, 255, 255)
local color = MYADDON_COLOR
```
Reason: A flat local is faster to read because it avoids repeated table lookups and benefits from Lua's cheapest variable access path.


```lua
local jobName = ply:getDarkRPVar("job")

-- instead of:
-- local jobName = ply:GetNWString("job")
```
Reason: `ply:getDarkRPVar("job")` is DarkRP's supported API for the synced job name, while `GetNWString("job")` reaches into the underlying network storage directly and is less correct and less maintainable.


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


```lua
for ent in ents.Iterator() do
    -- visit every entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient choice for visiting every entity because it avoids building the table that `ents.GetAll()` returns.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if ent ~= ply then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a common fast built-in for "near player" spatial queries, avoids scanning all entities manually, and fits radial proximity better than making `FindInPVS` the default choice.


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

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

    return out
end
```
Reason: `player.GetAll()` only iterates players, and `DistToSqr` avoids the square root work of full distance checks, so this skips scanning non-player entities and reduces per-call cost.


```lua
for i = 1, n do
    -- tight counting work
end
```
Reason: Numeric `for` is generally faster for `1..n` counting in Garry's Mod Lua because the loop control is handled by the VM with less per-iteration overhead than a manual `while` increment/check.


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

-- Faster: one hook dispatch per tick, handlers loop players internally if needed.
hook.Run("MyPlayersTick", players)

-- Slower:
-- for i = 1, #players do
--     hook.Run("MyPlayerTick", players[i])
-- end
```
Reason: One `hook.Run` avoids repeated global hook lookup, vararg packing, and dispatcher overhead every tick; the per-player loop multiplies that overhead by player count.


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

draw.SimpleText(hp, "DermaDefault", x1, y1, color_white)
draw.SimpleText(hp .. "%", "DermaDefault", x2, y2, color_white)
draw.RoundedBox(4, x3, y3, hp * 2, 16, Color(200, 60, 60))
```
Reason: Cache `LocalPlayer():Health()` once per frame and reuse it to avoid three repeated function calls in the hot `HUDPaint` path.


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

function PANEL:Paint(w, h)
    for i = 1, self.ItemCount do
        surface.SetDrawColor(COLOR_WHITE)
        -- draw work here
    end
end
```
Reason: Reuse one Color object outside the paint loop so the client stops allocating a new table every iteration.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

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

    -- use ply here instead of calling LocalPlayer() repeatedly
    if ply:Alive() then
        -- hot-path logic
    end
end)
```
Reason: Cache the `LocalPlayer()` result once and reuse the local reference in hot paths, with a validity refresh only when needed, so you avoid repeated global lookup/function call overhead.


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

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

    -- Unit vectors: dot product is cosine of the angle between them.
    -- If they are looking toward each other, their aim directions point opposite ways,
    -- so the dot product is near -1.
    return aimA:Dot(aimB) <= COS_FACING_EACH_OTHER
end
```
Reason: Using a dot-product threshold on normalized aim vectors avoids `math.acos`, giving the same facing test much cheaper and with less temporary math.


```lua
SomeHelper(ply)
```
Reason: For helpers you control, the direct function call is generally a bit faster because `:` adds implicit method lookup/self passing overhead, and it also avoids pretending the helper is part of the player metatable when it is not.


```lua
MsgN("hot path debug: ", someValue)
```
Reason: `MsgN` writes directly to the console with less overhead than `print`, so it is the usual faster choice for hot-path debug output in Garry's Mod Lua.


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


```lua
-- Faster than chaining DarkRP fn combinators for hot paths: one tight loop, no closures, no intermediate lists.
local players = player.GetAll()
local out = {}
local n = 0

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

return out
```
Reason: A single indexed loop avoids the extra function calls, closure dispatch, and intermediate table allocations that `fn.Filter(...):Map(...)` style pipelines add in plain Lua hot paths.


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

local function RefreshActivePlayers()
    activePlayers = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "MyAddon.RefreshActivePlayers", function()
    RefreshActivePlayers()
end)

hook.Add("PlayerDisconnected", "MyAddon.RefreshActivePlayers", function()
    RefreshActivePlayers()
end)

hook.Add("Tick", "MyAddon.DoWork", function()
    for i = 1, #activePlayers do
        local ply = activePlayers[i]
        if IsValid(ply) then
            -- per-player work here
        end
    end
end)
```
Reason: This avoids allocating and traversing a fresh `player.GetAll()` result every tick, and only rebuilds the player list when membership changes.


```lua
local healthCache = {}

local function SetCachedHealth(ply, value)
    healthCache[ply:EntIndex()] = value
end

local function GetCachedHealth(ply)
    return healthCache[ply:EntIndex()]
end
```
Reason: Numeric array-style lookup by `EntIndex()` avoids repeated player table field/hash access and is typically faster for hot read paths than `ply.someField`.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays are faster to iterate because they use Lua's compact array part and avoid string-key hash lookups.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw numeric channels avoids the extra table/object access from a `Color` value and is the faster style in a hot draw path.


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


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

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

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

-- hot path
local function DoThing(players)
    for i = 1, #players do
        local ply = players[i]
        local steamId = GetSteamIDCached(ply)
        -- use steamId here
    end
end

-- optional invalidation on disconnect if you want explicit cleanup
hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIdCache[ply] = nil
end)
```
Reason: This avoids repeated Lua-to-engine method calls on the hot path by computing each player's SteamID once and reusing it, while weak keys prevent stale player references from being kept alive.


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

local result = table.concat(pieces)
print(result)
```
Reason: `table.concat` avoids creating a new intermediate string on every append, so it is much faster and uses less memory than repeated `..` concatenation in a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the extra Lua-side wrapper and corner setup work inside `draw.RoundedBox(0, ...)`, so it is slightly cheaper for plain rectangles.


```lua
local font = "Trebuchet24"
local x, y = 32, 32
local colorWhite = Color(255, 255, 255)
local text = "FPS: 144"

surface.SetFont(font)

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetTextColor(colorWhite)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetTextPos` + `surface.DrawText` is the leanest common path for a single-line string because it avoids the extra alignment, vararg, and outline work in `draw.DrawText` and especially `draw.SimpleTextOutlined`.


```lua
local len = #tbl
```
Reason: `#` is the preferred built-in length operator for sequential array-like tables in Garry's Mod Lua.


```lua
local t = {}

-- When you only need to discard the old contents, this is generally faster:
t = {}
```
Reason: Rebinding `t` to a new table avoids clearing every existing entry one by one, so it is usually faster for large sequential tables unless other references must keep pointing at the same table.


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

if allowed[value] then
    -- value exists in the set
end
```
Reason: Key lookup in a set-style table is O(1) on average, while `table.HasValue` scans a list linearly with O(n) cost.


```lua
local t = { x = 1, y = 2, z = 3 }
```
Reason: For a small table with known fields, the table constructor is typically faster and cleaner because it creates and populates the table in one step instead of doing extra field assignments after `{}`.


```lua
local value = seq[math.random(#seq)]
```
Reason: For a sequential array, direct indexing with a random integer avoids the extra key traversal and non-array handling overhead in `table.Random`.


```lua
local xx = x * x
```
Reason: `x * x` avoids the exponent operator's extra overhead and is the usual fastest form in a tight Garry's Mod Lua loop.


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


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: `ents.Iterator()` walks entities lazily, so this filters `prop_physics` without first allocating a table of all map entities.


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


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


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    print("Received MyAddon.Sync")
end)
```
Reason: `net.Receive` registers a callback that runs whenever the `MyAddon.Sync` net message arrives.


```lua
-- Slow in a hot path: allocates a new Angle every time.
local ang1 = Angle(0, 0, 0)

-- Faster: reuse the engine-provided shared zero angle.
local ang2 = angle_zero
```
Reason: `angle_zero` avoids repeated `Angle(0, 0, 0)` allocations and constructor work; only use it when you will not mutate the shared angle.


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

local color = MYADDON_COLOR
```
Reason: A local variable is fastest for hot reads because it avoids repeated table indexing (`myaddon.config.color`) and global lookup overhead.


```lua
local jobName = ply:getDarkRPVar("job")

-- Not preferred:
-- local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is DarkRP’s intended API for the networked job name, while `GetNWString("job")` bypasses the gamemode-specific contract.


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


Answer must contain 1 through 1 candidate loops.

```lua
if ents.Iterator then
    for _, ent in ents.Iterator() do
        -- use ent
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- use ent
    end
end
```
Reason: `ents.Iterator()` avoids building the full entity table and is the preferred efficient full-entity iterator; `ipairs(ents.GetAll())` is a compatible fallback.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if ent ~= ply then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a common fast default for nearby-entity queries because it does direct radius-based broad-phase lookup without the heavier visibility/path semantics of `FindInPVS`.


```lua
local player_GetAll = player.GetAll

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

    local radiusSqr = radius * radius
    local players = player_GetAll()
    local count = 0

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

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

    return out
end
```
Reason: It only scans players instead of every entity and uses squared-distance checks, so it avoids the extra entity work and sqrt cost from `ents.FindInSphere` plus filtering.


```lua
for i = 1, n do
    -- tight loop body
end
```
Reason: Numeric `for` is generally faster for 1..n counting in Lua because the loop control stays in the VM with less per-iteration overhead than a manual `while` increment/check.


```lua
hook.Add("Think", "NotifyPlayersOnce", function()
    local players = player.GetAll()

    -- Faster: one hook dispatch, handlers iterate players themselves.
    hook.Run("MyPlayersTick", players)

    -- Slower:
    -- for i = 1, #players do
    --     hook.Run("MyPlayerTick", players[i])
    -- end
end)

hook.Add("MyPlayersTick", "MyCustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom per-player logic here
    end
end)
```
Reason: One `hook.Run` call avoids repeating hook dispatch, vararg setup, and listener iteration for every player, so total overhead is lower.


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

    draw.SimpleText(health, "DermaLarge", 32, 32, color_white)
    draw.RoundedBox(4, 32, 72, health * 2, 20, Color(200, 50, 50))
    draw.SimpleText("HP: " .. health, "Trebuchet24", 32, 100, color_white)
end)
```
Reason: Cache `LocalPlayer()` and `:Health()` once per frame to avoid repeating the same function calls three times inside `HUDPaint`.


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

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

    for i = 1, self.BarCount do
        surface.DrawRect((i - 1) * 8, 0, 6, h)
    end
end
```
Reason: `Color(...)` allocates/builds a color object each iteration; caching one immutable white color outside the paint loop removes that repeated work.


```lua
local sin = math.sin

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


```lua
local LocalPlayer = LocalPlayer
local IsValid = IsValid

local cachedLocalPlayer

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

    return cachedLocalPlayer
end

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

    local health = ply:Health()
    local armor = ply:Armor()
    draw.SimpleText(health .. " / " .. armor, "DermaDefault", 16, 16, color_white)
end)
```
Reason: This caches both the global function lookup and the player entity, so repeated code uses a local reference and only refreshes it when the cached player is invalid.


```lua
local LOOK_DOT = 0.8 -- about 37 degrees of slack

local function RoughlyLookingAtEachOther(plyA, plyB)
    local toB = (plyB:EyePos() - plyA:EyePos()):GetNormalized()
    local toA = -toB

    return plyA:GetAimVector():Dot(toB) >= LOOK_DOT
       and plyB:GetAimVector():Dot(toA) >= LOOK_DOT
end
```
Reason: Dot products avoid `math.acos`, so this stays cheap while still checking that each player's aim vector points toward the other player's eye position within a tunable threshold.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally the better choice for a helper you control because a local/direct function call avoids the per-call table method lookup behind `ply:SomeHelper()`, and `obj:method()` is mainly for real object methods, not free helpers.


```lua
MsgN("debug: hot path hit")
```
Reason: `MsgN` is typically faster than `print` in Garry's Mod for a simple debug line because it writes directly to the console without `print`'s extra argument formatting overhead.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: `for i = 1, #numbers do` is the fastest typical choice for a large dense numeric array in Garry's Mod Lua because it avoids the iterator overhead of `pairs` and `ipairs` and does direct indexed access.


```lua
-- Equivalent to a filter->map pipeline, but done in one pass.
local function collectPoliceNames(players)
    local out = {}
    local outN = 0

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

    return out
end

local policeNames = collectPoliceNames(player.GetAll())
```
Reason: A single indexed loop is usually faster than DarkRP's `fn` filter/map chain because it avoids extra closures, function-call overhead, and intermediate tables while doing the same work in one pass.


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

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

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

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


```lua
local tempByEntIndex = {}

local function SetTempData(ply, value)
    tempByEntIndex[ply:EntIndex()] = value
end

local function GetTempData(ply)
    return tempByEntIndex[ply:EntIndex()]
end

hook.Add("PlayerDisconnected", "ClearTempData", function(ply)
    tempByEntIndex[ply:EntIndex()] = nil
end)
```
Reason: A plain Lua table indexed by `EntIndex()` avoids per-read entity field/metatable lookup, so hot reads are cheaper; clearing on disconnect prevents slot reuse bugs.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: A sequential number-indexed array is faster to iterate than a string-keyed map because it uses dense integer keys and a simple numeric loop instead of hash-key traversal.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw numbers is faster in a hot draw path because it avoids the extra Color/table argument handling that the `Color` overload requires.


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


```lua
local SID_CACHE_KEY = "__cached_steamid"

local function GetSteamIDCached(ply)
    local sid = ply[SID_CACHE_KEY]
    if sid ~= nil then
        return sid
    end

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

-- Hot path
for i = 1, #players do
    local ply = players[i]
    local steamID = GetSteamIDCached(ply)
    -- use steamID
end
```
Reason: `ply:SteamID()` crosses into engine code each call, while a cached Lua field turns repeated lookups for the same player into a cheap table access.


```lua
local pieces = {}

for i = 1, 100000 do
    pieces[i] = "part" .. i
end

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

-- Fast: collect pieces, then join once.
local fast = table.concat(pieces)
```
Reason: `table.concat` is faster because it avoids reallocating and copying the whole accumulated string on every `..` append.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is a more direct rectangle draw path, while `draw.RoundedBox(0, ...)` adds wrapper overhead you do not need for non-rounded boxes.


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

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(FONT)
    surface.SetTextColor(R, G, B, A)
    surface.SetTextPos(X, Y)
    surface.DrawText(TEXT)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the leanest path here for a single-line string; `draw.DrawText` does extra layout/alignment work and `draw.SimpleTextOutlined` adds multiple outline passes.


```lua
local len = #myTable
```
Reason: `#` is the preferred built-in length operator for sequential array-like tables; it is direct and avoids `table.Count`, which is for counting all keys.


```lua
t = {}
```
Reason: `t = {}` is generally faster because it allocates a new table instead of clearing every existing element one by one like `table.Empty(t)`, as long as you do not need to preserve other references to the same table.


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

if allowed[className] then
    -- value exists in the set
end
```
Reason: `table.HasValue` scans a list linearly, while a keyed lookup table gives near-constant-time membership checks.


```lua
-- Faster
local t = {
    a = 1,
    b = 2,
    c = 3,
}

-- Slower
-- local t = {}
-- t.a = 1
-- t.b = 2
-- t.c = 3
```
Reason: For a small table with known keys, the table constructor does the work in one allocation/initialization step and avoids separate field-set operations after `{}`.


```lua
local function randomSequential(t)
    return t[math.random(#t)]
end

local value = randomSequential(mySequentialTable)
```
Reason: For a dense 1..n array, direct indexing with `math.random(#t)` avoids the extra generic work `table.Random` does to support non-sequential tables.


```lua
local squared = x * x
```
Reason: `x * x` is the preferred fast form in a tight loop because it avoids function-call overhead and exponentiation dispatch.


```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` visits every connected player without allocating the temporary table that `player.GetAll()` creates.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: `ents.Iterator()` streams entities one by one, so it avoids allocating a table of all entities before filtering by class.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod guard and returns false for `nil`, `NULL`, and removed/invalid entities, so method calls only run when the reference is still usable.


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


```lua
-- Slow: allocates a new Angle every call.
local function slow()
    return Angle()
end

-- Fast: reuse one scratch Angle and zero it in place.
local scratchAng = Angle()

local function fast()
    scratchAng:SetUnpacked(0, 0, 0)
    return scratchAng
end
```
Reason: Reusing one `Angle` avoids per-call allocation and GC churn; zeroing the same object in place is cheaper than constructing a new `Angle()` on every hot-path call.


```lua
local addonColor = myaddon.config.color
local color = addonColor
```
Reason: A local is fastest in Lua; `myaddon.config.color` does multiple table lookups, and a global is also a table lookup through `_G`.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred over ply:GetNWString("job")
```
Reason: `job` is a DarkRPVar, so `getDarkRPVar` is the supported DarkRP API and does not depend on generic NWString state.


```lua
local maxDist = 256

if vec1:DistToSqr(vec2) <= maxDist * maxDist then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root used by actual distance calculation, so it is the preferred and faster method for threshold checks when you compare against the squared threshold.


```lua
for _, ent in ents.Iterator() do
    -- Visit every entity here.
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient full-entity iterator because it walks the engine list directly without allocating the temporary table that `ents.GetAll()` creates; use `ents.GetAll()` only if you specifically need a snapshot table.


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

for i = #nearby, 1, -1 do
    local ent = nearby[i]
    if not IsValid(ent) or ent == ply then
        nearby[i] = nearby[#nearby]
        nearby[#nearby] = nil
    end
end

-- `nearby` now contains valid entities near the player.
```
Reason: `ents.FindInSphere` is one of the commonly faster built-in `FindIn*` choices for a cheap near-player query because it stays engine-side, uses spatial partitioning, and matches a radius lookup directly without `FindInPVS` visibility semantics.


```lua
local player_GetAll = player.GetAll

local function FindPlayersNear(pos, radius)
    local radiusSqr = radius * radius
    local players = player_GetAll()
    local out, n = {}, 0

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

    return out
end
```
Reason: This scans only players instead of all entities, avoids per-entity class checks, and uses squared distance to skip the expensive square root.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` is generally faster for 1..n counting in Garry's Mod Lua because it uses the language's built-in counted-loop path and avoids the extra manual condition and increment work of a `while` loop.


```lua
-- Faster: one hook dispatch per tick, then iterate players inside the listener.
hook.Add("Tick", "NotifyAllPlayersOnce", function()
    hook.Run("MyPerTickPlayers", player.GetAll())
end)

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

-- Slower:
-- hook.Add("Tick", "NotifyEachPlayerSeparately", function()
--     local players = player.GetAll()
--     for i = 1, #players do
--         hook.Run("MyPerTickPlayer", players[i])
--     end
-- end)
```
Reason: `hook.Run` has dispatch overhead, so calling it once per tick and looping players inside the handler does less total work than re-entering the hook system once per player.


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

    local health = ply:Health()
    local healthText = tostring(health)

    draw.RoundedBox(4, 20, 20, health * 2, 24, Color(200, 60, 60))
    draw.SimpleText(healthText, "Trebuchet24", 28, 22, color_white)
    draw.SimpleTextOutlined(healthText, "Trebuchet24", 28, 22, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, color_black)
end)
```
Reason: Cache `LocalPlayer():Health()` once per `HUDPaint` so the three draw calls reuse one value instead of repeating the method lookup and call in the same frame.


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

function PANEL:Paint(w, h)
    for i = 1, 100 do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(0, i * 4, w, 2)
    end
end
```
Reason: `Color(255, 255, 255)` creates a new color object each iteration; reusing one cached color removes per-frame allocations and GC churn.


```lua
local sin = math.sin

for i = 1, 1000000 do
    local y = sin(i)
    -- hot-loop work
end
```
Reason: Caching `math.sin` in a local avoids repeated table/global lookups inside the hot loop, which is a small but common Lua micro-optimization.


```lua
local getLocalPlayer = LocalPlayer
local cachedLocalPlayer

local function LP()
    local ply = cachedLocalPlayer
    if not IsValid(ply) then
        ply = getLocalPlayer()
        if not IsValid(ply) then return nil end
        cachedLocalPlayer = ply
    end
    return ply
end

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

    if ply:Alive() then
        -- use ply here instead of calling LocalPlayer() again
    end
end)
```
Reason: It avoids repeated global/function lookup and player resolution on hot paths by caching the local player and only refreshing when that entity becomes invalid.


```lua
local function RoughlyLookingAtEachOther(a, b, dotThreshold)
    dotThreshold = dotThreshold or 0.8 -- higher = stricter

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

    return a:GetAimVector():Dot(aToB) >= dotThreshold
       and b:GetAimVector():Dot(bToA) >= dotThreshold
end
```
Reason: Dot products avoid `math.acos`, so this stays fast and directly checks whether each player's aim vector points close enough toward the other player's eye position.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster for a helper you control because it can be a direct function call and avoids the extra table/metatable method lookup behind `ply:SomeHelper()`, though the gap is usually small outside hot paths.


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


```lua
local nums = someSequentialNumberTable

for i = 1, #nums do
    local v = nums[i]
    -- use v
end
```
Reason: `numeric for` avoids iterator overhead and direct integer indexing is typically faster than `ipairs`, while `pairs` is for generic table traversal and is usually the slowest for a dense sequential array.


```lua
local IsValid = IsValid

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

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

        if IsValid(ply) and ply:Alive() and ply:isCP() then
            n = n + 1
            out[n] = ply:Nick()
        end
    end

    return out
end

local policeNames = getPoliceNames(player.GetAll())
```
Reason: A single indexed loop fuses filter and map into one pass, avoids fn closure/combinator overhead and intermediate tables, and is usually faster in GMod Lua.


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

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

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

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

        -- per-player work here
        -- Example: if ply:Alive() then ... end
    end
end)
```
Reason: `player.GetAll()` creates/traverses a player list every call, so moving that work to join/leave hooks keeps the hot `Tick` loop to a cheap cached-table scan.


```lua
local tempByPlayerId = {}

local function SetTemp(ply, value)
    tempByPlayerId[ply:EntIndex()] = value
end

local function GetTemp(ply)
    return tempByPlayerId[ply:EntIndex()]
end

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

-- hot read path
local id = ply:EntIndex()
local value = tempByPlayerId[id]
```
Reason: A plain Lua table indexed by `EntIndex()` avoids Garry's Mod entity field/metatable lookup on each read, so hot temporary per-player reads are faster than `ply.someField`.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays use Lua's array part and a numeric `for` loop, which iterates faster than traversing string-keyed maps with `pairs`.


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

hook.Add("HUDPaint", "HotDraw", function()
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(100, 100, 200, 40)
end)
```
Reason: Passing raw channel numbers avoids the extra Color object/table path and any per-frame allocation, so it is the lower-overhead call style for hot draw code.


```lua
local steamId64 = "76561198000000000"
local row = sql.QueryRow("SELECT cash FROM players WHERE steamid64 = " .. sql.SQLStr(steamId64))
```
Reason: Local SQLite via GMod's `sql` library is typically lower latency on a single server because it avoids network round trips and remote database overhead.


```lua
local PLAYER = FindMetaTable("Player")

function PLAYER:GetSteamIDCached()
    local sid = self._cachedSteamID
    if sid == nil then
        sid = self:SteamID()
        self._cachedSteamID = sid
    end
    return sid
end

hook.Add("PlayerInitialSpawn", "WarmSteamIDCache", function(ply)
    ply._cachedSteamID = ply:SteamID()
end)

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    ply._cachedSteamID = nil
end)

-- Hot path
local function ProcessPlayers(players)
    for i = 1, #players do
        local ply = players[i]
        local sid = ply._cachedSteamID or ply:GetSteamIDCached()

        -- use sid here
    end
end
```
Reason: It pays the `SteamID()` method call once per player, then reuses a plain field read in the hot path, which is cheaper than repeated userdata method dispatch.


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

-- Fast:
local parts = {}

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

local big = table.concat(parts, "")
```
Reason: `table.concat` builds the final string in one pass, avoiding the repeated reallocation and full-string copying caused by `..` inside a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is a more direct filled-rectangle call and avoids the extra helper/corner-handling overhead in `draw.RoundedBox(0, ...)`.


```lua
local SetFont = surface.SetFont
local SetTextColor = surface.SetTextColor
local SetTextPos = surface.SetTextPos
local DrawText = surface.DrawText

local FONT = "DermaDefaultBold"
local TEXT = "Single line every frame"
local X, Y = 24, 24

hook.Add("HUDPaint", "FastSingleLineText", function()
    SetFont(FONT)
    SetTextColor(255, 255, 255, 255)
    SetTextPos(X, Y)
    DrawText(TEXT)
end)
```
Reason: Direct `surface` text calls are faster for a single-line draw because they avoid the extra wrapper work in `draw.DrawText` and the multiple text passes used by `draw.SimpleTextOutlined`.


```lua
local len = #myTable
```
Reason: `#` is the preferred way to get the length of a sequential array-like table; `table.Count` is for non-sequential keys and does extra work.


```lua
t = {}
```
Reason: `t = {}` is generally faster because it replaces the large sequential table instead of iterating and niling every element like `table.Empty(t)`; only keep `table.Empty(t)` when other code must retain the same table reference.


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

if allowed[weaponClass] then
    -- value exists
end
```
Reason: A set-style table uses direct key lookup with average O(1) cost, while `table.HasValue` walks a list linearly with O(n) cost.


```lua
-- Faster for a small table with known fields:
local t = {
    x = 10,
    y = 20,
    name = "npc",
}

-- Slower:
-- local t = {}
-- t.x = 10
-- t.y = 20
-- t.name = "npc"
```
Reason: Putting known fields directly in the table constructor is faster because Lua can build the table in one step with fewer bytecode operations and fewer hash inserts than creating `{}` and assigning each field afterward.


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

local value = randomSequential(myTable)
```
Reason: `table.Random` handles general tables, but a sequential table can skip that overhead and pick a random numeric index directly with `t[math.random(#t)]`.


```lua
local y = x * x
```
Reason: `x * x` is the fast preferred form in a tight loop because it avoids the slower exponentiation operator `x ^ 2`.


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


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


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers a Think hook callback under the `MyAddon.Think` identifier so Garry's Mod can invoke it every frame.


```lua
if IsValid(ent) then
    -- safe to call methods on ent here
end
```
Reason: `IsValid` checks that the entity reference still points to a live, usable entity before you call methods on it.


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


```lua
local zero = angle_zero

-- hot path
local a = zero
-- use `a` as a zeroed Angle without allocating a new one

-- slower
local b = Angle(0, 0, 0)
```
Reason: `angle_zero` is a shared zeroed Angle, so reusing it avoids repeated `Angle()` allocations in hot paths.


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

local color = myaddon_config_color
```
Reason: a flat local avoids repeated table lookups, so it is faster for a hot, frequently read setting than `myaddon.config.color`.


```lua
ply:getDarkRPVar("job")
```
Reason: `getDarkRPVar("job")` is DarkRP’s job API and is the preferred way to read a player’s job name; `GetNWString("job")` is the lower-level networked-value fallback and may not match DarkRP’s own state handling.


```lua
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root, so it is the preferred method for a threshold check.


```lua
for ent in ents.Iterator() do
    -- visit every entity here
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient way to traverse all entities when you want to iterate them directly without building a full `ents.GetAll()` table first.


```lua
local ply = Entity(1) -- or any player entity
if not IsValid(ply) then return end

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

for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) and ent ~= ply then
        -- cheap per-entity filtering here
    end
end
```
Reason: `ents.FindInSphere` is one of the faster built-in spatial queries in common GMod benchmarks, and it is the simplest cheap broad-phase query for entities near a player.


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

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

    return out
end
```
Reason: `player.GetAll()` gives only players, so it avoids building and filtering a mixed entity list from `ents.FindInSphere`; `DistToSqr` also skips the square-root cost.


```lua
for i = 1, n do
    -- tight counting loop
end
```
Reason: Numeric `for` is generally faster than `while` in Garry's Mod Lua because the VM optimizes it as a dedicated loop form with less per-iteration overhead.


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

-- Slower: one hook call per player per tick.
for i = 1, #players do
    hook.Run("MyCustomTick", players[i])
end
```
Reason: One `hook.Run` call avoids repeating hook dispatch overhead for every player, so it is cheaper than calling it once per player each tick.


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

-- use hp for all three draw calls below
-- draw first bar based on hp
-- draw second bar based on hp
-- draw third bar based on hp
```
Reason: Cache `LocalPlayer()` and `:Health()` once per frame so the hook does one player lookup and one health read instead of repeating both three times.


```lua
local white = color_white

for i = 1, count do
    surface.SetDrawColor(white)
    -- paint work here
end
```
Reason: Reuses Garry's Mod's shared `color_white` instead of allocating a new `Color(255, 255, 255)` table every iteration.


```lua
local sin = math.sin

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


```lua
local LocalPlayer = LocalPlayer

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

    -- use lp many times here instead of calling LocalPlayer() repeatedly
end)
```
Reason: Caching the global function in a local avoids repeated global table lookup, and storing the player in a local inside the hot path avoids calling `LocalPlayer()` multiple times in the same frame.


```lua
local function RoughlyLookingAtEachOther(p1, p2, threshold)
    threshold = threshold or 0.90 -- closer to 1.0 = stricter

    local a1 = p1:EyeAngles():Forward()
    local a2 = p2:EyeAngles():Forward()
    local to2 = (p2:EyePos() - p1:EyePos()):GetNormalized()
    local to1 = -to2

    return a1:Dot(to2) >= threshold and a2:Dot(to1) >= threshold
end
```
Reason: Dot products are cheaper than acos and directly test how aligned each player's aim vector is with the direction to the other player.


```lua
SomeHelper(ply)
```
Reason: For a helper you control, the free-function style is generally a bit faster and easier to optimize because it avoids method-call lookup and implicit self dispatch; the difference is usually small, but `SomeHelper(ply)` is the preferred style.


```lua
MsgN("debug: hot path hit")
```
Reason: `MsgN` writes straight to the console and avoids `print`'s extra formatting overhead, so it is the lighter choice for hot-path debug output.


```lua
-- Fastest typical loop for a dense array-like table
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: Numeric `for` is typically fastest for large sequential tables because it avoids the iterator overhead of `pairs` and `ipairs`.


```lua
-- Faster than chaining DarkRP fn combinators: one pass, no temp closures, no temp lists.
local function filterMap(list, keep, map)
  local out = {}
  local n = 0

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

  return out
end

-- Example:
-- local result = filterMap(players.GetAll(),
--   function(p) return p:Alive() end,
--   function(p) return p:Nick() end
-- )
```
Reason: This does filter and map in a single numeric for loop, so it avoids the extra function-call overhead, iterator chaining, and intermediate tables that fn combinators usually add.


```lua
local cachedPlayers = {}

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

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

hook.Add("Tick", "ProcessCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- work with ply here
        end
    end
end)

refreshPlayers()
```
Reason: `player.GetAll()` allocates and walks the player list; caching it and refreshing only on join/leave removes that repeated per-tick work.


```lua
local tempData = setmetatable({}, { __mode = "k" }) -- weak keys so player entries can vanish

-- write
function SetTempValue(ply, value)
    tempData[ply] = value
end

-- read
function GetTempValue(ply)
    return tempData[ply]
end
```
Reason: a single shared lookup table avoids creating extra fields on each player object and gives you a tight `tempData[ply]` read path for hot per-player state.


Answer must contain 0 through 1 candidate loops.

```lua
local array = { "a", "b", "c" }
local map = { first = "a", second = "b", third = "c" }

-- Faster for fixed-order iteration:
for i = 1, #array do
    local value = array[i]
end

-- Slower for this use case:
for key, value in pairs(map) do
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because Lua can traverse the array part directly, while string-keyed tables use hash lookups.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw r,g,b,a numbers avoids constructing or unpacking a `Color` object, which is the lighter choice for a hot draw path.


```lua
sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: Local SQLite is typically lower latency for a single Garry's Mod server because it avoids network round trips and uses an on-disk embedded database.


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

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

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

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

-- hot path usage:
-- local sid = GetSteamIDCached(ply)
```lua
Reason: Caches each player's SteamID once and reuses it on hot paths, avoiding repeated method calls while the weak-key table lets entries fall out when the player entity is no longer referenced.


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

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


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips the rounded-box path and is the lighter direct rectangle draw for non-rounded fills.


```lua
local fontName = "HudHintTextLarge"
local text = "Hello world"
local x, y = 100, 100

surface.SetFont(fontName)
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.SetTextColor` + `surface.DrawText` is the lightest option here; it avoids the extra layout/shadow/outline work and higher-level wrapper overhead in `draw.DrawText` and especially `SimpleTextOutlined`.


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


```lua
-- Fastest when you only need to discard the old contents and do not need
-- other references to see the cleared table.
t = {}

-- Use table.Empty(t) only when you must keep the same table object
-- for existing references.
```
Reason: `t = {}` usually wins for repeatedly discarding a large table because it avoids walking and clearing every slot; `table.Empty(t)` only helps when you must preserve the original table reference.


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

if set[item] then
    -- item exists in the set
end
```
Reason: A keyed lookup is O(1) on average, while `table.HasValue` scans a list linearly and gets slower as the list grows.


```lua
-- Faster / smaller: use the table constructor when fields are known up front.
local t = { x = 1, y = 2, z = 3 }

-- Slower: create empty table, then assign fields.
local u = {}
u.x = 1
u.y = 2
u.z = 3
```
Reason: The constructor does the allocation and field initialization in one step, while separate assignments add extra writes and lookups; for a small known table, the constructor is the faster choice.


```lua
local t = {"a", "b", "c", "d"}
local value = t[math.random(#t)]
```
Reason: For a sequential table, indexing directly with `math.random(#t)` avoids `table.Random`'s extra table iteration and is faster.


```lua
local y = x * x
```
Reason: `x * x` is the direct square operation and is faster and clearer than calling `math.pow` or `x ^ 2` in a tight Lua loop.


The recommendation changes the set of visited players.

```lua
for _, ply in ipairs(player.GetHumans()) do
    -- your code here
end
```
Reason: `player.GetHumans()` returns the currently connected human players, and `ipairs` is the idiomatic way to iterate that list in order.


```lua
for ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: `ents.Iterator()` yields entities lazily, so it scans the map without first materializing a full entity table.


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


```lua
if not IsValid(ent) then return end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check for whether an entity reference still points to a live, usable entity before calling methods on it.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the message here
end)
```
Reason: `net.Receive` is the Garry's Mod API for registering a handler for an incoming net message by name.


```lua
-- Slow: allocates a new Angle every call.
local function makeZeroAngle_slow()
    return Angle()
end

-- Faster in a hot path: reuse one scratch Angle and reset it.
-- Only use this when the caller consumes it immediately and does not keep it.
local ZERO_ANGLE = Angle()

local function makeZeroAngle_fast()
    ZERO_ANGLE:Zero()
    return ZERO_ANGLE
end
```


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

local c = myaddon_color
```
Reason: A flat local is faster to read than `myaddon.config.color` because it avoids repeated table lookups.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP exposes the job label through `getDarkRPVar("job")`; `NWString("job")` is an internal networked variable and is not the preferred API.


```lua
if vec1:DistToSqr(vec2) <= threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root and is the right choice when you only need a distance threshold check.


```lua
for ent in ents.Iterator() do
    -- visit every entity here
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator for walking all entities without building a full table first.


```lua
local pos = ply:GetPos()
local radius = 256
local entsNear = ents.FindInSphere(pos, radius)

for _, ent in ipairs(entsNear) do
    -- process ent
end
```
Reason: `ents.FindInSphere` is a fast built-in broadphase query for “near a player” checks and is usually the simplest performant choice when you do not need the extra cost of `FindInPVS`.


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

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

    return out
end
```
Reason: `player.GetAll()` skips scanning every entity, and `DistToSqr` avoids the square root cost of `Distance`, which is faster when you only care about players.


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


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

hook.Run("MyCustomTick", players)
```
Reason: one hook dispatch per tick is cheaper than one hook dispatch per player, because it avoids repeated hook lookup, argument packing, and Lua/C boundary overhead.


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

    local hp = lp:Health()

    draw.SimpleText(hp, "DermaDefault", 20, 20, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(math.Clamp(hp, 0, 100), "DermaDefault", 20, 60, color_white)
end)
```
Reason: `LocalPlayer():Health()` is computed once per frame and reused, so the hook avoids repeating the same lookup and method call three times.


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

for i = 1, n do
    surface.SetDrawColor(WHITE)
    -- paint work
end
```
Reason: `Color(255, 255, 255)` allocates or looks up a color object each pass; hoisting one shared white color avoids repeated work in the hot loop.


```lua
local sin = math.sin

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


```lua
local LocalPlayer = LocalPlayer

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

    -- use lp here
end)
```
Reason: `LocalPlayer` is resolved once into a local upvalue, so repeated calls skip the global table lookup.


```lua
local LOOK_DOT = 0.94 -- about a 20 degree cone; tune as needed

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

    local aPos = plyA:EyePos()
    local bPos = plyB:EyePos()

    local aToB = bPos - aPos
    local bToA = aPos - bPos

    if aToB:LengthSqr() == 0 or bToA:LengthSqr() == 0 then return false end

    aToB:Normalize()
    bToA:Normalize()

    return plyA:GetAimVector():Dot(aToB) >= LOOK_DOT
       and plyB:GetAimVector():Dot(bToA) >= LOOK_DOT
end
```
Reason: Dot products give the same facing test as an angle check without `math.acos`, so this is cheaper and fast for per-tick use.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally faster for a helper you control because it avoids the method lookup and colon-call sugar overhead; the difference is usually small, but the direct function call is the cheaper path.


```lua
MsgN("debug: ", value)
```
Reason: `MsgN` writes straight to the console with less formatting overhead than `print`.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: `numeric for` is typically fastest for a large sequential array-like table because it avoids iterator overhead; `ipairs` is slower and `pairs` is the least suitable for dense arrays.


```lua
local function filter_map(list, pred, map)
  local out = {}
  local n = 0

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

  return out
end

-- Example: DarkRP-style list work, but fused into one pass.
local names = filter_map(players.GetAll(), function(p)
  return IsValid(p) and p:Alive() and not p:isArrested()
end, function(p)
  return p:Nick()
end)
```
Reason: One numeric for-loop, no intermediate tables, no combinator chaining, and no `table.insert` overhead; that is less allocation and fewer Lua calls than a small fn pipeline.


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

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

hook.Add("PlayerDisconnected", "RefreshCachedPlayersLeave", function(ply)
    for i = #cachedPlayers, 1, -1 do
        if cachedPlayers[i] == ply then
            table.remove(cachedPlayers, i)
            break
        end
    end
end)

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- work with ply
    end
end)
```
Reason: `player.GetAll()` allocates and rebuilds the full player list every tick; caching it and updating only on join/leave removes that repeated work.


```lua
local PlayerData = setmetatable({}, { __mode = "k" }) -- weak keys; entries vanish when player entity is gone

local function GetPlayerData(ply)
    local data = PlayerData[ply]
    if data == nil then
        data = {}
        PlayerData[ply] = data
    end
    return data
end

-- write
local data = GetPlayerData(ply)
data.tempScore = 123

-- hot reads
local score = GetPlayerData(ply).tempScore
```
Reason: a plain Lua table keyed by the player entity avoids repeated entity-field lookup, and hot code can keep the returned data table in a local for faster reads.


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

for i = 1, #values do
  local v = values[i]
  -- use v
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because Lua can walk them with dense numeric access instead of hash lookups.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing raw numbers avoids creating or unpacking a `Color` object on a hot draw path, so it is the faster call style.


```lua
local result = sql.QueryValue("SELECT money FROM player_data WHERE steamid = " .. sql.SQLStr(steamID64))
```
Reason: Local SQLite is typically lower latency for a single GMod server because it avoids network round-trips and remote MySQL connection overhead.


```lua
local steamid_cache = setmetatable({}, { __mode = "k" }) -- weak keys: entries drop when the player entity disappears

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

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

-- hot path usage
-- local sid = SteamIDCached(ply)
```
Reason: `ply:SteamID()` is an expensive repeated lookup here, so a weak-key memoization table returns the same string after the first call per player and lets stale entries fall away automatically.


```lua
-- Slow: repeated .. rebuilds the string over and over.
local out = ""
for i = 1, 10000 do
    out = out .. "piece" .. i .. ","
end

-- Fast: collect parts, then join once.
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece"
    parts[#parts + 1] = i
    parts[#parts + 1] = ","
end

local out_fast = table.concat(parts)
```
Reason: `..` copies the full string each time, so it gets slower as the string grows; `table.concat` builds once from parts and is much faster for thousands of pieces.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` does extra rounded-box plumbing; `surface.DrawRect` is the direct filled-rectangle draw call and is a bit cheaper for plain rectangles.


```lua
local font = "MyFont"
local text = "Hello, world"
local x, y = 100, 100
local color = color_white

surface.SetFont(font)
surface.SetTextColor(color)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.SetTextColor` + `surface.DrawText` is the leanest path for a single line; `draw.DrawText` and especially `SimpleTextOutlined` do extra layout/alignment/outline work every frame.


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


```lua
-- Faster when you can replace the reference:
t = {}

-- Use table.Empty(t) only when you must keep the same table object.
```
Reason: `t = {}` is generally faster because it allocates a new empty table instead of clearing every key in the old one; `table.Empty(t)` mutates the existing table and is typically slower for large tables.


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

if allowed[weaponName] then
    -- found
end
```
Reason: A keyed lookup is O(1) average, while `table.HasValue` scans the list linearly and gets slower as the list grows.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: The constructor is faster because it builds the table with its fields in one step, instead of creating an empty table and doing extra assignments afterward.


```lua
local idx = math.random(#seq)
local value = seq[idx]
```
Reason: For a sequential array, direct indexing with `math.random(#seq)` avoids the extra work `table.Random` does to scan/handle generic table keys.


```lua
local y = x * x
```
Reason: `x * x` avoids the function call and overhead of `math.pow` in a tight loop.


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 players as an array-like table, so `ipairs` is the direct loop for visiting each connected player.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- visit each prop_physics here
end
```
Reason: `ents.FindByClass` returns only entities of the requested class, so it avoids building a table of every entity in the map first.


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


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


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


```lua
-- Fast: reuse the built-in zero angle instead of allocating a new one each time.
local ZERO_ANGLE = angle_zero

-- Example hot-path use:
-- someFunc(ZERO_ANGLE)
```
Reason: `angle_zero` is a shared zeroed `Angle` value, so reusing it avoids repeated `Angle()` construction and allocation in hot paths.


```lua
local addon_color = Color(255, 128, 0)
local c = addon_color
```
Reason: A local is faster to read than a nested table lookup or global access in Lua, so it is the best choice for a frequently read setting.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP exposes the job through its own `DarkRPVar` API, so this is the preferred, supported way instead of reading the raw networked string.


```lua
if pos1:DistToSqr(pos2) <= threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root cost of `DistTo`, which is the right check when you only need to know whether two vectors are within a threshold.


```lua
for ent in ents.Iterator() do
    -- visit each entity here
end
```
Reason: `ents.Iterator()` walks the entity list without allocating a full table, so it is the preferred efficient loop for visiting every entity.


```lua
local function GetNearbyEntities(ply, radius)
    local pos = ply:GetPos()
    local out = ents.FindInSphere(pos, radius)

    local filtered = {}
    for i = 1, #out do
        local ent = out[i]
        if ent ~= ply and IsValid(ent) then
            filtered[#filtered + 1] = ent
        end
    end

    return filtered
end
```
Reason: `ents.FindInSphere` is a fast built-in broad-phase query for “nearby entities” and is commonly benchmarked as one of the better choices for radius checks, without using `FindInPVS` as the default.


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

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

    return found
end
```
Reason: `player.GetAll()` only walks players, not every entity, and `DistToSqr` avoids a square root per check.


```lua
local sum = 0
for i = 1, n do
    sum = sum + i
end
```
Reason: Numeric `for` is generally faster in Lua for tight counted loops because the VM handles the counter and limit more efficiently than a manual `while` increment and compare.


```lua
hook.Add("Think", "NotifyPlayersEachTick", function()
    local players = player.GetAll()
    hook.Run("MyCustomPlayerTick", players)
end)
```
Reason: one `hook.Run` per tick is faster than one `hook.Run` per player because it avoids repeated hook dispatch and Lua/C boundary overhead.


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

    local health = lp:Health()

    draw.SimpleText(health, "DermaDefault", 100, 100, color_white)
    draw.SimpleText(health, "DermaDefault", 100, 120, color_white)
    draw.SimpleText(health, "DermaDefault", 100, 140, color_white)
end)
```
Reason: Cache `LocalPlayer()` and `:Health()` once per frame so the three draw calls reuse the same value instead of repeating the lookup.


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

hook.Add("HUDPaint", "MyPaintLoop", function()
    for i = 1, 100 do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(i, 10, 1, 1)
    end
end)
```
Reason: Reusing one prebuilt `Color` avoids allocating a new color object on every iteration.


```lua
local sin = math.sin

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


```lua
local LocalPlayer = LocalPlayer
local IsValid = IsValid

local cachedLP

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

    return cachedLP
end

-- hot path
local lp = GetLocalPlayerCached()
if IsValid(lp) then
    -- reuse `lp` instead of calling LocalPlayer() repeatedly
end
```
Reason: it turns repeated global/function lookups into one cached local reference that you reuse in hot code.


```lua
local function RoughlyLookingAtEachOther(plyA, plyB, cosLimit)
    if not (IsValid(plyA) and IsValid(plyB)) then return false end

    cosLimit = cosLimit or 0.7 -- about 45 degrees; raise for a tighter check

    local aAim = plyA:GetAimVector() -- normalized
    local bAim = plyB:GetAimVector() -- normalized

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

    return aAim:Dot(aToB) >= cosLimit
       and bAim:Dot(bToA) >= cosLimit
end
```
Reason: `Dot` plus a cosine threshold is fast and avoids `math.acos` while still testing whether each player is facing the other.


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


```lua
MsgN("hot path debug")
```
Reason: `MsgN` writes directly to the console with less overhead than `print` when you do not need Lua-style formatting or multiple-argument joining.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: `for i = 1, #t do` is typically fastest for a dense sequential array-like table because it avoids the iterator overhead of `pairs` and `ipairs`.


```lua
-- Faster than chaining DarkRP fn filter/map combinators: one pass, no intermediates.
local function filterMap(list, keep, map)
    local out = {}
    local n = 0

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

    return out
end

-- Example: keep active players and map to nicknames.
local names = filterMap(player.GetAll(),
    function(p) return IsValid(p) and p:Alive() end,
    function(p) return p:Nick() end
)
```
Reason: One tight loop with no combinator chaining, no extra closures per stage, and no intermediate lists, so it does less allocation and dispatch work.


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

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

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

hook.Add("Think", "UseCachedPlayersInsteadOfPlayerGetAll", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- work with ply
        end
    end
end)
```
Reason: `player.GetAll()` allocates and repopulates a table every tick; caching once and refreshing only on join/leave removes that repeated per-frame work.


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

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

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

-- hot path
local v = tempByPly[ply]
```
Reason: a weak-key side table avoids per-entity field lookup on `ply` and keeps reads as a direct table index by player reference.


```lua
-- Faster for iteration: sequential numeric indices
local values = { "alpha", "beta", "gamma", "delta" }

for i = 1, #values do
  local v = values[i]
  -- use v
end
```
Reason: Sequential number-indexed arrays are faster to iterate in Lua because they use direct array-style access, while string-keyed maps require hash lookup for each element.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Separate numeric RGBA arguments avoid the extra Color-object handling and are the faster call style in a hot draw path.


```lua
local row = sql.QueryRow("SELECT value FROM playerdata WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: For a single Garry's Mod server with no cross-server sync, local SQLite is typically lower latency because it stays in-process/on-disk, while MySQL adds network round trips and remote server overhead.


```lua
local steamid_cache = setmetatable({}, { __mode = "k" }) -- weak keys, no leak after players go away

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

-- hot path
for _, ply in ipairs(player.GetAll()) do
    local sid = GetSteamIDFast(ply)
    -- use sid repeatedly here instead of ply:SteamID()
end
```
Reason: `SteamID()` is a repeated cross-boundary lookup; caching it once per player removes duplicate work in hot loops.


```lua
-- Slow: repeated string rebuilding in a loop
-- local out = ""
-- for i = 1, #pieces do
--     out = out .. pieces[i]
-- end

-- Fast: collect pieces, join once
local parts = {}
for i = 1, #pieces do
    parts[#parts + 1] = pieces[i]
end

local out = table.concat(parts)
```
Reason: `table.concat` joins all pieces in one pass, so it avoids the repeated reallocations and copying caused by `..` inside a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips the rounded-rect path and is the direct primitive for solid rectangles, so it is a bit cheaper than `draw.RoundedBox(0, ...)`.


```lua
local fontName = "Trebuchet18"
local text = "Hello"

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(fontName)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(50, 50)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` with cached font/color/position is the lightest of these options; `draw.DrawText` and especially `SimpleTextOutlined` do extra work.


```lua
local len = #myTable
```
Reason: For a sequential array-like table, the preferred Lua length operator is `#`; `table.Count` is for counting all keys in a non-sequential table.


```lua
t = {}
```
Reason: `t = {}` is generally faster because it just makes `t` point at a new empty table, while `table.Empty(t)` has to clear the existing table in place; use `table.Empty(t)` only when other references must see the table emptied.


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

if allowed[value] then
    -- value exists in the set
end
```
Reason: `allowed[value]` is an O(1) hash lookup, while `table.HasValue` scans a list linearly and gets slower as the list grows.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: The table constructor is faster here because Lua can create and populate the table in one step, while `t = {}` followed by assignments does extra separate writes/lookups.


```lua
local function FastRandom(seq)
    local n = #seq
    if n == 0 then return nil end
    return seq[math.random(n)]
end
```
Reason: Sequential tables are array-like, so direct indexing with `math.random(#seq)` avoids `table.Random`'s generic table traversal overhead.


```lua
local y = x * x
```
Reason: `x * x` is the fastest clear form in Lua for squaring because it avoids function-call overhead and exponentiation machinery.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- loop body
end
```
Reason: `player.GetAll()` returns the connected player list, and `ipairs` walks it in order.


```lua
for _, ent in pairs(ents.FindByClass("prop_physics")) do
    -- visit ent here
end
```
Reason: `ents.FindByClass` returns only `prop_physics` entities, so you avoid building a full map-wide entity table first.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers the callback under the `Think` hook with the identifier `MyAddon.Think`, so it runs every frame.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the Garry's Mod guard for nil, removed, or otherwise invalid entities before calling methods on them.


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


```lua
local ANGLE_ZERO = angle_zero -- read-only cached zero angle

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

-- fast:
local ang = ANGLE_ZERO
```
Reason: `angle_zero` is preallocated, so reusing it avoids constructing a new `Angle` userdata and the GC churn from `Angle()`.


```lua
local addon_color = Color(255, 255, 255)
local color = addon_color
```
Reason: a local/upvalue read is faster than repeated `myaddon.config.color` table lookups, and faster than a global.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: `getDarkRPVar("job")` is DarkRP's public accessor for the synced job name, so it is the supported API instead of reading the raw NWString directly.


```lua
if v1:DistToSqr(v2) < threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root, so it is faster and the right choice when you only need a threshold check.


```lua
for _, ent in ents.Iterator() do
    -- visit ent
end
```
Reason: `ents.Iterator()` walks entities without materializing `ents.GetAll()`'s table, so it is the better choice when you only need to visit each entity once.


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

local nearby = ents.FindInBox(mins, maxs)
```
Reason: `FindInBox` is one of the fastest built-in broad-phase spatial queries in common GMod benchmarks, and it fits a cheap “near this player” check without the visibility semantics of `FindInPVS`.


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

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

    return out
end
```
Reason: `player.GetAll()` iterates only players, so it avoids scanning every entity in `ents.FindInSphere`, and `DistToSqr` skips the expensive square root.


```lua
for i = 1, n do
    -- work
end
```
Reason: a numeric `for` loop is generally faster than `while` for a tight 1..n counter loop in GMod Lua.


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

-- Slower: dispatches once per player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomTickPlayer", ply)
end
```
Reason: `hook.Run` has fixed dispatch overhead, so one call per tick is cheaper than one call per player.


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

    draw.SimpleText("HP: " .. health, "Trebuchet24", 20, 20, color_white)
    draw.SimpleText("Health: " .. health, "Trebuchet24", 20, 40, color_white)
    draw.RoundedBox(4, 20, 60, health * 2, 16, color_red)
end)
```
Reason: Cache `LocalPlayer()` and `:Health()` once per frame instead of calling `LocalPlayer():Health()` three times.


```lua
local WHITE = color_white

hook.Add("HUDPaint", "FastPaintExample", function()
    surface.SetDrawColor(WHITE)
    surface.DrawRect(10, 10, 100, 20)
end)
```
Reason: `Color(255,255,255)` allocates a new color table; reusing `color_white` or a cached local avoids that per-iteration work.


```lua
local sin = math.sin

for i = 1, n do
    sum = sum + sin(i)
end
```
Reason: caching `math.sin` in a local avoids repeated global/table lookups inside the hot loop.


```lua
local LocalPlayer = LocalPlayer

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

    -- Reuse lp instead of calling LocalPlayer() repeatedly.
    if lp:Alive() then
        -- hot-path logic here
    end
end)
```
Reason: `LocalPlayer` is cached as a local upvalue, and the player entity is fetched once per hot path so the same `lp` value can be reused without repeated lookups.


```lua
local LOOK_DOT = 0.70710678 -- cos(45°); raise for stricter, lower for looser

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

    local ab = b:EyePos() - a:EyePos()
    ab:Normalize()

    return a:GetAimVector():Dot(ab) >= LOOK_DOT
       and b:GetAimVector():Dot(-ab) >= LOOK_DOT
end
```
Reason: Dot products measure alignment directly, so you avoid `math.acos` and keep the check to a few vector ops.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally a little faster and clearer for a helper you control because it avoids method-style lookup/sugar; the difference is tiny, but the plain function call is the leaner choice.


```lua
MsgN("debug: ", value)
```
Reason: `MsgN` is the direct console output primitive in Garry's Mod, so it avoids `print`'s extra formatting work in a hot path.


```lua
local sum = 0
local n = #t

for i = 1, n do
    sum = sum + t[i]
end
```
Reason: Numeric `for` is typically fastest for a dense sequential array in Garry's Mod Lua; `ipairs` adds iterator overhead and `pairs` is the slowest and least predictable for arrays.


```lua
local function fastFilterMap(src, predicate, mapper)
    local out = {}
    local n = 0

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

    return out
end

-- Example: keep active players and map to their job names.
local jobNames = fastFilterMap(players, function(p)
    return IsValid(p) and p:Alive()
end, function(p)
    return p:getDarkRPVar("job")
end)
```
Reason: one pass, no intermediate tables, and fewer closure/combinator calls than chaining DarkRP fn filter/map helpers.


```lua
if SERVER then
    local cachedPlayers = player.GetAll()
    local playersDirty = false

    local function InvalidatePlayerCache()
        playersDirty = true
    end

    hook.Add("PlayerInitialSpawn", "PlayerCacheJoin", InvalidatePlayerCache)
    hook.Add("PlayerDisconnected", "PlayerCacheLeave", InvalidatePlayerCache)

    hook.Add("Tick", "UseCachedPlayers", function()
        if playersDirty then
            cachedPlayers = player.GetAll()
            playersDirty = false
        end

        for i = 1, #cachedPlayers do
            local ply = cachedPlayers[i]
            -- per-player work here
        end
    end)
end
```
Reason: `player.GetAll()` now runs only after a join or leave marks the cache dirty, so the per-tick hook reuses the same table instead of rebuilding it every frame.


```lua
local PlayerTemp = setmetatable({}, { __mode = "k" }) -- weak keys so removed players do not leak

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

local function GetTemp(ply)
    return PlayerTemp[ply]
end

-- usage
SetTemp(ply, {
    someField = value
})

local temp = GetTemp(ply)
local field = temp and temp.someField
```
Reason: a plain upvalue table lookup is cheaper than going through `ply.someField`, and weak keys keep temporary per-player data from leaking after the player is gone.


```lua
-- Faster for iteration: sequential numeric array
local values = {
    "health",
    "armor",
    "speed",
    "ammo",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because Lua can traverse the array part with simple indexed access instead of hashing string keys.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Raw numeric arguments are the faster hot-path style than passing a Color object.


```lua
local rows = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: Local SQLite is usually lower latency for a single Garry's Mod server because it stays on the same machine and avoids the network round trip and remote connection overhead of MySQL.


```lua
local steamid_cache = {}

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

hook.Add("PlayerDisconnected", "SteamIDCached_Clear", function(ply)
    steamid_cache[ply] = nil
end)

-- hot path
local sid = SteamIDCached(ply)
if sid == target_sid then
    -- ...
end
```
Reason: memoizes the SteamID per player so repeated hot-path checks do a table lookup instead of calling into GMod every time.


```lua
-- Slow: repeated .. concatenation copies the whole string over and over.
-- local s = ""
-- for i = 1, n do
--   s = s .. chunks[i]
-- end

local parts = {}
for i = 1, n do
  parts[i] = chunks[i]
end

local s = table.concat(parts)
```
Reason: `table.concat` builds the final string in one pass, so it avoids the repeated reallocations and copying that make `..` in a loop slow.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, so it avoids the extra rounded-box logic in `draw.RoundedBox(0, ...)`.


```lua
local font = "Trebuchet24"
local text = "Hello world"

hook.Add("HUDPaint", "FastTextExample", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` with the `surface.*` setup calls is the lowest-overhead path for plain single-line text; `draw.DrawText` and `SimpleTextOutlined` add extra wrapper, alignment, and outline work.


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


```lua
t = {}
```
Reason: `t = {}` is generally faster because it drops the old table and makes a fresh empty one, while `table.Empty(t)` has to walk and clear the existing table; use `table.Empty(t)` only if other code still holds that table object.


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

for _, v in ipairs(list) do
    set[v] = true
end

if set[weaponClass] then
    -- value exists in the set
end
```
Reason: direct table lookup is O(1) on average, while `table.HasValue` scans the list linearly.