```lua
local function findPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local players = {}

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

    return players
end
```
Reason: Iterating only players avoids allocating and filtering all nearby entities, while squared-distance checks avoid an expensive square root.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` loops use LuaJIT's specialized loop instructions and are generally faster for fixed counting ranges.


```lua
-- Faster: dispatch the custom hook once per tick.
hook.Add("Tick", "MyAddon.NotifyPlayers", function()
    hook.Run("MyAddon.PlayerTick", player.GetAll())
end)

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

-- Slower: dispatches the entire hook chain once for every player.
-- hook.Add("Tick", "MyAddon.NotifyPlayers", function()
--     local players = player.GetAll()
--     for i = 1, #players do
--         hook.Run("MyAddon.PlayerTick", players[i])
--     end
-- end)
```
Reason: One hook dispatch avoids repeating Garry's Mod hook lookup and callback traversal for every player; listeners can loop over the shared player list once.


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

    draw.SimpleText(healthText, "DermaLarge", 20, 20, color_white)
    draw.SimpleText(healthText, "DermaDefault", 20, 50, color_white)
    draw.SimpleText(healthText, "DermaDefaultBold", 20, 75, color_white)
end)
```
Reason: Cache the health value once per frame and reuse it across all three draw calls.


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

for i = 1, count do
    surface.SetDrawColor(WHITE)
    -- paint work
end
```
Reason: Reusing one color avoids allocating a new table and creating garbage on every iteration.


```lua
local sin = math.sin

for i = 1, iterations do
    local value = sin(i)
end
```
Reason: Binding `math.sin` to a local avoids repeated global and table lookups inside the hot loop.


```lua
local LocalPlayer = LocalPlayer

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

    local health = ply:Health()
    local armor = ply:Armor()
end)
```
Reason: Caching the global function in a local avoids repeated global-table lookups while preserving a current LocalPlayer() result.


```lua
local function AreFacingEachOther(plyA, plyB)
    return plyA:GetAimVector():Dot(plyB:GetAimVector()) <= -0.8
end
```
Reason: Aim vectors are normalized, so their dot product is the cosine; a negative threshold detects opposing directions without `math.acos`.


```lua
SomeHelper(ply)
```
Reason: It avoids the player/metatable method lookup; make `SomeHelper` a local/upvalue for the fastest controlled-helper call.


```lua
MsgN("debug line")
```
Reason: `MsgN` avoids `print`’s extra argument-formatting overhead for a preformatted console line.


```lua
local n = #numbers
for i = 1, n do
    local value = numbers[i]
    -- use value
end
```
Reason: Numeric `for` avoids iterator-function overhead and is typically fastest for dense sequential tables.


```lua
-- Equivalent filter + map, fused into one pass over a dense array.
local function paidPlayerNames(players, minimumSalary)
    local names = {}
    local count = 0

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:getDarkRPVar("salary") >= minimumSalary then
            count = count + 1
            names[count] = ply:Nick()
        end
    end

    return names
end

local names = paidPlayerNames(player.GetAll(), 100)
```
Reason: One indexed loop fuses filter and map work, avoiding combinator callbacks and intermediate tables.


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

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

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

hook.Add("Think", "UseCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        -- per-player work
    end
end)
```
Reason: `player.GetAll()` runs only when membership changes, so the per-tick hook reuses the cached table.


```lua
local temporaryByPlayer = {}

local function SetTemporary(ply, value)
    temporaryByPlayer[ply] = value
end

local function GetTemporary(ply)
    return temporaryByPlayer[ply]
end

hook.Add("PlayerDisconnected", "clear_temporary_player_data", function(ply)
    temporaryByPlayer[ply] = nil
end)
```
Reason: A Lua table keyed by the player avoids Player userdata field/metamethod lookup on the hot read path.


```lua
local values = {
    "alpha",
    "bravo",
    "charlie",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: A dense 1-based numeric array uses Lua's array storage and avoids the hash lookups needed by string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numeric channels avoids Color-table argument handling on each hot-path call.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
```
Reason: Local SQLite avoids remote network round trips, so it is typically lower latency for a single server.


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

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

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

-- hot path
local steamID = CachedSteamID(ply)
```
Reason: The cache performs `SteamID()` only once per player object while weak keys and disconnect cleanup prevent stale entries.


Answer must contain 0 through 0 candidate loops.

```lua
-- Slow: repeatedly reallocates and copies the growing string.
local slow = ""
for i = 1, #pieces do
    slow = slow .. pieces[i]
end

-- Fast: collect pieces, then concatenate once.
local result = table.concat(pieces)
```
Reason: table.concat avoids repeatedly reallocating and copying the already-built prefix for every piece.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect avoids draw.RoundedBox’s Lua wrapper and zero-radius branch.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.DrawText` avoids the alignment, sizing, and extra outline draw passes performed by `draw.DrawText` and `draw.SimpleTextOutlined`.


```lua
local length = #myTable
```
Reason: `#` is the preferred length operator for a sequential, array-like table.


```lua
t = {}
```
Reason: Rebinding allocates a new empty table instead of clearing every existing entry; use `table.Empty(t)` only when other references must observe the same table being emptied.


```lua
-- Slow for repeated membership checks: O(n) scan each time.
local allowedList = { "admin", "moderator", "vip" }
if table.HasValue(allowedList, player:GetUserGroup()) then
    -- allowed
end

-- Fast: build a lookup set once, then check in average O(1).
local allowedGroups = {
    admin = true,
    moderator = true,
    vip = true,
}

if allowedGroups[player:GetUserGroup()] then
    -- allowed
end
```
Reason: `table.HasValue` linearly scans an array on every check, while a keyed lookup table performs average constant-time membership checks.


```lua
local data = {
    x = x,
    y = y,
    z = z,
}
```
Reason: The constructor preallocates space for its known fields, avoiding incremental table growth from starting with `{}`.


```lua
local element = items[math.random(#items)]
```
Reason: A sequential table supports constant-time length lookup and numeric indexing, avoiding table.Random's general-purpose traversal.


```lua
local squared = x * x
```
Reason: Multiplication avoids the slower exponentiation operator in a tight loop.


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

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


```lua
for ent in ents.Iterator("prop_physics") do
    -- Process ent here
end
```
Reason: ents.Iterator("prop_physics") yields matching entities one at a time without first building a table of all entities.


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


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the reference is non-nil and still points to a valid, usable entity.


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


```lua
local a = angle_zero
```
Reason: `angle_zero` reuses Garry’s Mod’s predefined zero angle, avoiding a new `Angle()` allocation in the hot path.


```lua
local configColor = Color(255, 255, 255)
local color = configColor
```
Reason: A local variable avoids repeated table lookups and global-environment lookup, making frequent reads faster.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores job data in its own replicated variables, so `ply:getDarkRPVar("job")` is the preferred API over the generic `ply:GetNWString("job")`.


```lua
if pos1:DistToSqr(pos2) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: `DistToSqr` avoids the unnecessary square-root calculation needed by actual distance methods.


```lua
for ent in ents.Iterator() do
    -- Process ent here
end
```
Reason: ents.Iterator() visits every entity efficiently without first allocating the full table returned by ents.GetAll().


```lua
local origin = ply:GetPos()
local radius = 256
local radiusSqr = radius * radius
local nearby = {}

for _, ent in ipairs(ents.FindInBox(
    origin - Vector(radius, radius, radius),
    origin + Vector(radius, radius, radius)
)) do
    if ent:GetPos():DistToSqr(origin) <= radiusSqr then
        nearby[#nearby + 1] = ent
    end
end
```
Reason: `ents.FindInBox` is a fast built-in broad-phase query; the squared-distance check keeps only entities inside the desired radius.


```lua
local function PlayersWithinRadius(origin, radius)
    local radiusSqr = radius * radius
    local nearby = {}

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

    return nearby
end
```
Reason: `player.GetAll()` iterates only players and avoids scanning unrelated entities and building/filtering the broader `ents.FindInSphere` result; squared distance also avoids square-root calculations.


```lua
for i = 1, n do
    -- counting work
end
```
Reason: A numeric `for` loop is generally faster than an equivalent `while` loop in Garry's Mod Lua because the Lua VM handles its counting and increment internally.


```lua
hook.Add("Tick", "NotifyPlayers", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)

hook.Add("CustomPlayerTick", "HandlePlayers", function(players)
    for _, ply in ipairs(players) do
        -- Custom logic for each player.
    end
end)
```
Reason: `hook.Run` dispatches the hook once per tick instead of repeating hook lookup and callback dispatch for every player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache LocalPlayer() and Health() once per frame instead of recomputing them for each draw call.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, w, h)
end
```
Reason: Create the Color object once and reuse it instead of allocating a new one on every paint iteration.


```lua
local sin = math.sin

for i = 1, 1000000 do
    local value = sin(i)
end
```
Reason: Local lookup is faster than repeatedly indexing the global `math` table in a hot loop.


```lua
local ply = LocalPlayer()

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

-- Hot path:
if IsValid(ply) then
    local name = ply:Nick()
end
```
Reason: Cache the player entity once and reuse the local variable instead of repeatedly calling LocalPlayer() in the hot path.


```lua
local function AreLookingAtEachOther(a, b, minDot)
    minDot = minDot or 0.7 -- roughly within 45 degrees

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

    return a:EyeAngles():Forward():Dot(aToB) >= minDot
       and b:EyeAngles():Forward():Dot(bToA) >= minDot
end
```
Reason: Dot products compare aim alignment against a cosine threshold, avoiding the expensive math.acos angle calculation.


```lua
SomeHelper(ply)
```
Reason: For a helper you control, a local or otherwise directly referenced function avoids the receiver method lookup that `ply:SomeHelper()` performs, while both pass `ply` as the first argument.


```lua
MsgN("debug line")
```
Reason: `MsgN` writes directly to the console with a newline and avoids `print`'s extra Lua-side handling, making it preferable in hot paths.


```lua
for i = 1, #values do
    local value = values[i]
    -- process(value)
end
```
Reason: A numeric for loop avoids pairs' key iteration overhead and ipairs' iterator-call overhead, making it typically fastest for dense sequential arrays.


```lua
local result = {}

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

    if ply:Alive() and ply:Team() == TEAM_POLICE then
        result[#result + 1] = ply:Nick()
    end
end
```
Reason: A single preallocated-result loop avoids the intermediate tables, iterator closures, and repeated function-call overhead created by chained DarkRP.fn filter/map combinators.


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

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

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

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

    local lastIndex = #cachedPlayers
    local lastPlayer = cachedPlayers[lastIndex]

    cachedPlayers[index] = lastPlayer
    playerIndex[lastPlayer] = index
    cachedPlayers[lastIndex] = nil
    playerIndex[ply] = nil
end

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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCache", addPlayer)
hook.Add("PlayerDisconnected", "UpdatePlayerCache", removePlayer)

hook.Add("Tick", "ProcessCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Process ply here.
    end
end)
```
Reason: The player list is maintained incrementally on join and leave, so each tick iterates the cached table without calling `player.GetAll()` or allocating a fresh list.


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

local function setTemporaryData(ply, value)
    playerData[ply] = value
end

local function getTemporaryData(ply)
    return playerData[ply]
end
```
Reason: A local table lookup avoids repeated entity field access and keeps the data private, while weak keys allow entries to be garbage-collected when players leave.


```lua
local values = { "one", "two", "three" }

for i = 1, #values do
    local value = values[i]
end
```
Reason: Sequential number-indexed arrays provide contiguous integer keys and support faster direct iteration than string-keyed maps.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate color numbers avoids constructing or reading a Color object in the hot draw path.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
```
Reason: Local SQLite is typically lower latency because it avoids network round trips to a remote MySQL server.


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

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

-- Hot path:
local steamID = CachedSteamID(ply)
```
Reason: SteamID is stable for a player, so the engine call happens once while weak keys let disconnected player objects be garbage-collected.


```lua
-- Slower: repeated concatenation creates many intermediate strings.
local result = ""
for _, piece in ipairs(pieces) do
    result = result .. piece
end

-- Faster: collect pieces, then concatenate once.
local buffer = {}
for i, piece in ipairs(pieces) do
    buffer[i] = piece
end

local result = table.concat(buffer)
```
Reason: table.concat builds the final string in one pass, avoiding repeated intermediate-string allocations and copying.


```lua
draw.NoTexture()
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the rounded-box helper's corner-radius handling, making it slightly faster for non-rounded rectangles.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.DrawText` avoids the wrapper and per-character outline work of `draw.SimpleTextOutlined`, making it the leanest choice for a single-line string.


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


```lua
-- Generally faster: replace the table reference.
t = {}
```
Reason: t = {} creates a new empty table in constant time, while table.Empty(t) removes entries from the existing table and takes time proportional to its size.


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

if allowed[weaponClass] then
    -- Value exists in the set.
end
```
Reason: Keyed table lookups are O(1) on average, while table.HasValue scans a list linearly.


```lua
-- Faster: initialize known fields in the constructor.
local player = {
    name = "Alyx",
    health = 100,
    alive = true,
}
```
Reason: The constructor creates the table and populates its known fields in one operation, avoiding separate assignment statements.


```lua
local value = items[math.random(#items)]
```
Reason: For a sequential table, direct indexing with a random numeric index avoids `table.Random`'s extra key-selection work.


```lua
local squared = x * x
```
Reason: Multiplication avoids the overhead of exponentiation while computing the square directly.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- Use ply here
end
```
Reason: player.GetAll() returns the currently connected players.


```lua
for ent in ents.Iterator("prop_physics") do
    -- Process ent here
end
```
Reason: ents.Iterator("prop_physics") lazily visits matching entities without first allocating a table of all entities.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the reference points to a valid, usable entity before calling methods on it.


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


```lua
local function freshZeroAngle()
    return angle_zero:Clone()
end

local a = freshZeroAngle()
```
Reason: `angle_zero:Clone()` copies the engine-provided zero angle through the native clone path, avoiding repeated `Angle()` constructor argument handling while still returning a fresh mutable Angle.


```lua
local addonColor = Color(255, 255, 255)
local color = addonColor
```
Reason: A local variable avoids repeated global and nested-table lookups, making frequent reads faster.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP’s `getDarkRPVar("job")` reads the framework-managed job value directly, while `ply:GetNWString("job")` is a generic networked variable and is not the preferred DarkRP API.


```lua
if pos1:DistToSqr(pos2) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: `DistToSqr` avoids the unnecessary square-root calculation required by the actual distance.


```lua
for ent in ents.Iterator() do
    -- Process ent here
end
```
Reason: ents.Iterator() visits every entity efficiently without first creating a full entity table.


```lua
local function findNearbyEntities(ply, radius)
    local pos = ply:GetPos()
    local offset = Vector(radius, radius, radius)
    return ents.FindInBox(pos - offset, pos + offset)
end
```
Reason: `ents.FindInBox` is typically faster than spherical entity searches in common benchmarks, making it a cheap broad-phase query near a player.


```lua
local function PlayersWithinRadius(origin, radius)
    local radiusSqr = radius * radius
    local nearby = {}

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

    return nearby
end
```
Reason: Iterating only players avoids scanning every entity, and `DistToSqr` avoids the square-root cost of distance calculations.


```lua
for i = 1, n do
    -- counting work
end
```
Reason: Numeric `for` loops are generally faster than equivalent `while` loops in Garry's Mod Lua because the runtime optimizes their counter management and bounds checks.


```lua
hook.Add("Tick", "NotifyPlayers", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)

hook.Add("CustomPlayerTick", "ProcessPlayers", function(players)
    for _, ply in ipairs(players) do
        -- Custom logic for ply.
    end
end)
```
Reason: One hook.Run call avoids per-player hook-dispatch overhead while still processing every player in the handler.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText("HP: " .. health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health .. "/100", "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache the player’s health once per frame and reuse the local value for all three draw calls.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(white)
    -- draw using the cached color
end
```
Reason: Create the Color object once instead of allocating it on every paint-loop iteration.


```lua
local sin = math.sin

for i = 1, iterations do
    local value = sin(i)
end
```
Reason: Local lookup is faster than repeatedly indexing the global `math` table and then resolving `sin` in the hot loop.


```lua
local player = LocalPlayer()

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

-- Use `player` in hot paths instead of calling LocalPlayer().
if IsValid(player) then
    -- player:Nick()
end
```
Reason: Cache the player entity once and reuse the local variable, avoiding repeated LocalPlayer() lookups while refreshing it after the client entity is initialized.


```lua
local function ArePlayersLookingAtEachOther(ply, other, threshold)
    threshold = threshold or 0.85 -- about 31.8 degrees

    local toOther = (other:GetShootPos() - ply:GetShootPos()):GetNormalized()
    local toPly = -toOther

    return ply:GetAimVector():Dot(toOther) >= threshold
       and other:GetAimVector():Dot(toPly) >= threshold
end
```
Reason: Dot products compare aim alignment directly against a cosine threshold, avoiding the expensive `math.acos` angle calculation.


```lua
SomeHelper(ply)
```
Reason: A plain Lua function call avoids method/metatable lookup overhead; both forms are otherwise semantically equivalent.


```lua
Msg("debug line\n")
```
Reason: `Msg` writes directly to the console without `print`'s extra formatting and line-prefix overhead.


```lua
for i = 1, #values do
    local value = values[i]
end
```
Reason: Numeric `for` is typically fastest for dense sequential arrays because it avoids the iterator overhead of `pairs` and `ipairs`.


```lua
local values = { 1, 2, 3, 4, 5, 6 }

-- DarkRP fn: two passes, callbacks, and an intermediate table.
local result = fn.Map(
    function(value)
        return value * 10
    end,
    fn.Filter(
        function(value)
            return value % 2 == 0
        end,
        values
    )
)

-- Faster: one pass, no intermediate table, fewer callback calls.
local faster = {}
local count = 0

for i = 1, #values do
    local value = values[i]
    if value % 2 == 0 then
        count = count + 1
        faster[count] = value * 10
    end
end
```
Reason: The fused loop performs filtering and mapping in one pass without allocating an intermediate table or invoking separate callbacks for each transform.


```lua
local cachedPlayers = {}

for _, ply in ipairs(player.GetAll()) do
    cachedPlayers[ply] = true
end

hook.Add("PlayerInitialSpawn", "CachePlayer", function(ply)
    cachedPlayers[ply] = true
end)

hook.Add("PlayerDisconnected", "UncachePlayer", function(ply)
    cachedPlayers[ply] = nil
end)

hook.Add("Think", "ProcessCachedPlayers", function()
    for ply in pairs(cachedPlayers) do
        if IsValid(ply) then
            -- Per-tick work for ply
        end
    end
end)
```
Reason: `player.GetAll()` runs only once during initialization; join and leave hooks update the cache, so each tick iterates the existing table directly.


```lua
local stamina = {}

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

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

SetStamina(ply, 100)
local current = GetStamina(ply)
```
Reason: A local table indexed by the player’s stable entity index avoids per-entity field lookup overhead and keeps hot reads on a fast local-table access path.


```lua
-- Slower for fixed-order iteration: string-keyed map
local map = {
    first = "a",
    second = "b",
    third = "c",
}

-- Faster: sequential number-indexed array
local array = {
    "a",
    "b",
    "c",
}

for i = 1, #array do
    local value = array[i]
end
```
Reason: Sequential number-indexed arrays use Lua's optimized array part and avoid string-key hashing during iteration.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: Separate numeric arguments avoid constructing or passing a Color object in the hot draw path.


```lua
local result = sql.Query("SELECT value FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: Local SQLite is typically lower latency because it avoids network round trips to a remote MySQL server.


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

local function getSteamID(ply)
    local steamID = steamIDCache[ply]
    if not steamID then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end

-- Hot path:
local steamID = getSteamID(ply)
```
Reason: Cache the stable SteamID by player object, avoiding repeated method calls while weak keys allow disconnected players to be garbage-collected.


```lua
-- Slower: repeated concatenation
local result = ""
for i = 1, 10000 do
    result = result .. pieces[i]
end

-- Faster: collect pieces, then concatenate once
local parts = {}
for i = 1, 10000 do
    parts[i] = pieces[i]
end

local result = table.concat(parts)
```
Reason: table.concat builds the final string in one pass, avoiding repeated intermediate-string allocations and copying.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the rounded-box helper's radius handling and is slightly cheaper for non-rounded rectangles.


```lua
local text = "Status: ready"
local font = "DermaDefault"
local x, y = 24, 24
local color = Color(255, 255, 255)

hook.Add("HUDPaint", "DrawStatus", function()
    surface.SetFont(font)
    surface.SetTextColor(color)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` avoids the extra setup and outline passes performed by `draw.DrawText` and `draw.SimpleTextOutlined`, making it the lowest-overhead choice for a plain single-line string.


```lua
local length = #myTable
```
Reason: The length operator `#` is preferred for sequential array-like tables.


```lua
-- Generally faster: replace the table.
t = {}
```
Reason: `t = {}` discards the old table in constant time, while `table.Empty(t)` iterates over entries and removes them; use `table.Empty(t)` only when existing references must keep seeing the same table.


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

if allowed[value] then
    -- value exists in the set
end
```
Reason: A keyed table performs near-constant-time lookups, while table.HasValue scans the list linearly.


```lua
-- Faster for known fields: initialize them in the constructor.
local playerData = {
    name = "Alyx",
    score = 100,
    alive = true,
}

-- Slower equivalent: create, then assign each field.
local otherData = {}
otherData.name = "Alyx"
otherData.score = 100
otherData.alive = true
```
Reason: The table constructor creates the table and initializes its known fields in one operation, avoiding separate field-assignment operations.


```lua
local value = items[math.random(#items)]
```
Reason: A sequential table lets you select a random index directly, avoiding the iteration and temporary work used by table.Random.


```lua
local squared = x * x
```
Reason: Multiplication is faster and avoids the overhead of calling `math.pow`.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Handle ply here
end
```
Reason: player.GetAll() returns all currently connected players, and ipairs iterates through them.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process ent here.
    end
end
```
Reason: `ents.Iterator()` traverses entities directly without first creating a table of all entities.


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


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: `IsValid(ent)` confirms the entity reference is still valid before calling methods on it.


```lua
net.Receive("MyAddon.Sync", function(length, player)
    -- Handle the incoming message here.
end)
```
Reason: net.Receive registers a callback for incoming messages with the specified name.


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

local function getZeroAngle()
    zeroAngle:Set(0, 0, 0)
    return zeroAngle
end
```
Reason: Reuse one Angle and reset its components instead of allocating a new Angle object on every call.


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

surface.SetDrawColor(ADDON_COLOR)
```
Reason: A local variable avoids repeated table indexing and is faster to read than a nested table path or global lookup.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores job data in its own synchronized variables, so `ply:getDarkRPVar("job")` is the preferred API over the generic `ply:GetNWString("job")`.


```lua
if vectorA:DistToSqr(vectorB) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: `DistToSqr` avoids the square-root cost of calculating the actual distance; compare it with the squared threshold.


```lua
for _, ent in ents.Iterator() do
    -- Visit each entity here.
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator for traversing every entity without first creating a full entity table.


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

    local pos = ply:GetPos()
    local bounds = Vector(radius, radius, radius)
    return ents.FindInBox(pos - bounds, pos + bounds)
end
```
Reason: `ents.FindInBox` is typically among the faster built-in spatial queries for cheap broad-phase proximity checks; filter the returned box results by exact distance only when needed.


```lua
local function FindPlayersNear(position, radius)
    local radiusSqr = radius * radius
    local nearby = {}

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

    return nearby
end
```
Reason: player.GetAll() scans only players, avoiding ents.FindInSphere's scan over every nearby entity, and DistToSqr avoids square-root calculations.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` loops are generally faster because the Lua VM handles counting, comparison, and incrementing more efficiently than a manual `while` loop.


```lua
hook.Add("Tick", "NotifyAllPlayers", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)

hook.Add("CustomPlayerTick", "HandlePlayers", function(players)
    for _, ply in ipairs(players) do
        -- Custom logic for each player.
    end
end)
```
Reason: Calling hook.Run once avoids repeated hook dispatch overhead while still allowing one loop over all players.


```lua
hook.Add("HUDPaint", "DrawHealth", function()
    local ply = LocalPlayer()
    local health = ply: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 instead of recomputing them for each draw call.


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

hook.Add("HUDPaint", "DrawSomething", function()
    surface.SetTextColor(white)
    draw.SimpleText("Hello", "DermaDefault", 100, 100, white)
end)
```
Reason: Create the Color object once outside the paint loop instead of allocating a new one every iteration.


```lua
local sin = math.sin

for i = 1, iterations do
    local value = sin(i)
end
```
Reason: Caching `math.sin` in a local avoids repeated table lookups in the hot loop.


```lua
local cachedPlayer

local function GetCachedLocalPlayer()
    if not IsValid(cachedPlayer) then
        cachedPlayer = LocalPlayer()
    end

    return cachedPlayer
end

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

    -- Use `player` throughout this hot path.
    local name = player:Nick()
end)
```
Reason: LocalPlayer() is resolved once after the entity becomes valid, then the cached player reference is reused.


```lua
local function AreRoughlyLookingAtEachOther(plyA, plyB, minDot)
    minDot = minDot or 0.5 -- 60 degrees or narrower

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

    local direction = delta:GetNormalized()
    return plyA:GetAimVector():Dot(direction) >= minDot
       and plyB:GetAimVector():Dot(-direction) >= minDot
end
```
Reason: Dot products compare aim alignment directly against a cosine threshold, avoiding the expensive math.acos angle calculation.


```lua
SomeHelper(ply)
```
Reason: A direct local function call avoids the extra `ply.SomeHelper` field or metatable lookup; use `:` only for actual methods.


```lua
MsgN("debug line")
```
Reason: MsgN writes directly to the Source console without print's extra Lua formatting overhead.


```lua
local count = #numbers
for i = 1, count do
    local value = numbers[i]
    -- process value
end
```
Reason: Numeric `for` avoids the iterator and key/value overhead of `pairs` and `ipairs`, making it typically fastest for dense sequential arrays.


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

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

    if IsValid(ply) and ply:Alive() then
        local money = ply:getDarkRPVar("money") or 0

        if money >= 10000 then
            richPlayers[#richPlayers + 1] = {
                player = ply,
                name = ply:Nick(),
                money = money
            }
        end
    end
end
```
Reason: One pass avoids intermediate tables and per-item callback overhead from separate filter/map combinators.


```lua
local cachedPlayers = {}

for _, ply in ipairs(player.GetAll()) do
    cachedPlayers[ply] = true
end

hook.Add("PlayerInitialSpawn", "UpdatePlayerCache", function(ply)
    cachedPlayers[ply] = true
end)

hook.Add("PlayerDisconnected", "UpdatePlayerCache", function(ply)
    cachedPlayers[ply] = nil
end)

hook.Add("Think", "ProcessCachedPlayers", function()
    for ply in pairs(cachedPlayers) do
        if IsValid(ply) then
            -- Per-tick player logic here.
        end
    end
end)
```
Reason: `player.GetAll()` runs once at setup, while join and leave hooks update the cache so the per-tick hook only iterates the current players.


```lua
local tempData = {}

tempData[ply] = value
local value = tempData[ply]

hook.Add("PlayerDisconnected", "ClearTempData", function(disconnectedPly)
    tempData[disconnectedPly] = nil
end)
```
Reason: A local Lua table lookup avoids the entity field/metamethod path used by `ply.someField`, making frequent reads cheaper.


```lua
local values = {
    "foo",
    "bar",
    "baz",
}

for i = 1, #values do
    local value = values[i]
    -- Use value here.
end
```
Reason: Sequential number-indexed arrays use Lua’s optimized array part and avoid string-key hashing overhead.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numbers avoids creating and passing a Color object in the hot draw path.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = '" .. sql.SQLStr(steamID, true) .. "'")
```
Reason: Local SQLite avoids network round trips, so it is typically lower latency for a single server without multi-server synchronization.


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

local function cachedSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID == nil then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end

-- Hot path:
local steamID = cachedSteamID(ply)
```
Reason: The player object is used as a weak cache key, so SteamID() runs once per live player while entries can be garbage-collected automatically.


```lua
-- Slower: repeated string concatenation
local result = ""
for _, piece in ipairs(pieces) do
    result = result .. piece
end

-- Faster: collect pieces, then concatenate once
local chunks = {}
for i, piece in ipairs(pieces) do
    chunks[i] = piece
end
local result = table.concat(chunks)
```
Reason: `table.concat` builds the final string in one pass, avoiding repeated intermediate string allocations and copies.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the rounded-box path and is slightly faster for non-rounded rectangles.


```lua
surface.CreateFont("BenchText", {
    font = "Tahoma",
    size = 18,
    weight = 500
})

local text = "Single-line text"
local font = "BenchText"

hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` avoids the extra wrapper and outline work performed by `draw.DrawText` and `draw.SimpleTextOutlined`; cache the font and text to minimize per-frame overhead.


```lua
local length = #myTable
```
Reason: The `#` operator is the preferred way to get the length of a sequential array-like table.


```lua
t = {}
```
Reason: Replacing the table is generally faster because it avoids iterating over and deleting existing entries; use table.Empty(t) only when preserving the table’s reference matters.


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

if allowed[value] then
    -- value exists in the set
end
```
Reason: A keyed-table lookup is approximately O(1), while table.HasValue scans the list linearly at O(n).


```lua
local point = {
    x = 10,
    y = 20,
    z = 30,
}
```
Reason: A table constructor initializes known fields during creation, avoiding separate assignment operations after allocation.


```lua
local value = values[math.random(#values)]
```
Reason: A sequential table supports direct indexed access, avoiding table.Random’s extra key-selection work.


```lua
local squared = x * x
```
Reason: Multiplication is faster and avoids the overhead of calling `math.pow(x, 2)`.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Handle ply here
end
```
Reason: player.GetAll() returns all currently connected players, and ipairs iterates through each player in the returned array.


```lua
for _, ent in ents.Iterator("prop_physics") do
    -- Use ent here.
end
```
Reason: ents.Iterator("prop_physics") yields matching entities lazily without creating a table of them first.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the reference is a valid, non-removed entity before calling methods on it.


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


```lua
-- Reuse Garry's Mod's zero-angle singleton when the consumer does not mutate it.
local zero = angle_zero

for i = 1, count do
    UseAngle(zero)
end
```
Reason: `angle_zero` reuses an existing zeroed Angle and avoids allocating a new Angle userdata on every iteration; do not use it with code that mutates the angle.


```lua
local ADDON_COLOR = Color(255, 0, 0)
local color = ADDON_COLOR
```
Reason: A local avoids global and nested-table lookups, making frequent reads faster.


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

-- Avoid:
local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` reads DarkRP’s authoritative job variable, while `GetNWString("job")` relies on a separate networked value that may be absent or stale.


```lua
if vec1:DistToSqr(vec2) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: `DistToSqr` avoids the unnecessary square-root calculation required by `Distance`.


```lua
for _, ent in ents.Iterator() do
    -- Process ent here
end
```
Reason: `ents.Iterator()` visits every entity without first allocating the table created by `ents.GetAll()`, making it the efficient iterator for this use case.


```lua
local radius = 256
local center = ply:WorldSpaceCenter()
local extent = Vector(radius, radius, radius)
local nearby = ents.FindInBox(center - extent, center + extent)

for _, ent in ipairs(nearby) do
    if ent ~= ply and ent:GetPos():DistToSqr(center) <= radius * radius then
        -- Use ent here.
    end
end
```
Reason: `ents.FindInBox` is commonly faster than spherical searches, and the distance check restores a true-radius result.


```lua
local function PlayersWithinRadius(position, radius)
    local radiusSqr = radius * radius
    local nearby = {}

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

    return nearby
end
```
Reason: `player.GetAll()` iterates only players instead of every entity, and `DistToSqr` avoids the square-root cost of a normal distance check.


```lua
for i = 1, n do
    -- work
end
```
Reason: A numeric `for` loop is generally faster for counting because Lua optimizes its index, limit check, and increment as a specialized loop.


```lua
hook.Add("Think", "NotifyAllPlayers", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)
```
Reason: One hook dispatch and one player-list lookup per tick avoids repeated hook.Run overhead for each player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache `LocalPlayer():Health()` once per frame and reuse the result across all three draw calls.


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

hook.Add("HUDPaint", "DrawItems", function()
    for i = 1, #items do
        surface.SetDrawColor(WHITE)
        -- draw item i
    end
end)
```
Reason: Create the Color object once outside the paint loop instead of allocating one every iteration.


```lua
local sin = math.sin

for i = 1, iterations do
    local value = sin(i)
end
```
Reason: A local lookup is cheaper than repeatedly resolving the global `math` table and its `sin` field in the hot loop.


```lua
local cachedPlayer

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

hook.Add("HUDPaint", "Example", function()
    if not IsValid(cachedPlayer) then return end

    cachedPlayer:ChatPrint("Using the cached local player")
end)
```
Reason: Cache the player entity once after initialization and reuse the local reference instead of calling LocalPlayer() repeatedly.


```lua
local FACING_DOT = 0.85 -- roughly within 32 degrees

local function AreLookingAtEachOther(a, b)
    local offset = b:GetShootPos() - a:GetShootPos()
    local lengthSqr = offset:LengthSqr()

    if lengthSqr == 0 then
        return false
    end

    local direction = offset / math.sqrt(lengthSqr)

    return a:GetAimVector():Dot(direction) >= FACING_DOT
       and b:GetAimVector():Dot(-direction) >= FACING_DOT
end
```
Reason: Dot products compare facing alignment directly, avoiding the slower math.acos angle calculation.


```lua
SomeHelper(ply)
```
Reason: A direct function call generally avoids the per-call method lookup that `ply:SomeHelper()` performs, while both pass `ply` explicitly.


```lua
MsgN("debug line")
```
Reason: `MsgN` writes directly to the console with a trailing newline and has less Lua-side overhead than `print`.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: For a dense sequential array, numeric `for` typically has less iterator overhead than `pairs` or `ipairs`.


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

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

    if IsValid(ply) and ply:Alive() and ply:getDarkRPVar("money") >= 1000 then
        names[#names + 1] = ply:Nick()
    end
end
```
Reason: A single indexed loop performs the filter and map together, avoiding intermediate tables, callback calls, and repeated traversal from separate `fn.Filter` and `fn.Map` operations.


```lua
local cachedPlayers = {}

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

refreshPlayerCache()

hook.Add("PlayerInitialSpawn", "RefreshPlayerCacheOnJoin", refreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", function()
    timer.Simple(0, refreshPlayerCache)
end)

hook.Add("Think", "ProcessCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Process ply here.
    end
end)
```
Reason: `player.GetAll()` runs only during initialization and join/leave events, so `Think` iterates the cached table without rebuilding the player list every tick.


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

-- Write
perPlayer[ply] = value

-- Hot-path read
local value = perPlayer[ply]
```
Reason: Direct Lua table access avoids the entity field lookup through Garry's Mod's metatable, while weak keys allow disconnected player data to be collected.


```lua
-- Faster for iteration: sequential number-indexed array
local values = { "red", "green", "blue" }

for i = 1, #values do
    local value = values[i]
end
```
Reason: Sequential number-indexed arrays use Lua's optimized array part and are faster to iterate than string-keyed maps.


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

surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Passing separate numeric components avoids the Color-object overload and per-call object handling.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = " .. SQLStr(steamID))
```
Reason: Local SQLite avoids network round trips, so it is typically lower latency for a single server without multi-server synchronization.


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

local function cachedSteamID(ply)
    local steamID = steamIDCache[ply]

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

    return steamID
end

-- Hot path:
local id = cachedSteamID(ply)
```
Reason: A weak-key cache calls `ply:SteamID()` once per player while allowing disconnected player entities to be garbage-collected.


```lua
local pieces = {}

for i = 1, thousands do
    pieces[i] = make_piece(i)
end

local result = table.concat(pieces)
```
Reason: table.concat joins all pieces efficiently in one operation, avoiding repeated intermediate-string allocations from `..`.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws directly, avoiding `draw.RoundedBox`'s Lua wrapper and radius check.


```lua
surface.CreateFont("HUD_SingleLine", {
    font = "Tahoma",
    size = 20,
    weight = 500,
})

local text = "Status: Online"
local font = "HUD_SingleLine"
local color = Color(255, 255, 255)
local textWidth

surface.SetFont(font)
textWidth = surface.GetTextSize(text)

hook.Add("HUDPaint", "DrawSingleLine", function()
    surface.SetFont(font)
    surface.SetTextColor(color)
    surface.SetTextPos((ScrW() - textWidth) * 0.5, 20)
    surface.DrawText(text)
end)
```
Reason: Direct `surface.*` calls avoid the extra helper overhead of `draw.DrawText` and `SimpleTextOutlined`; cache invariant font, color, and text measurements, and use `SimpleTextOutlined` only when an outline is required.


```lua
local length = #myTable
```
Reason: The `#` operator is the preferred way to get the length of a sequential array-like table.


```lua
t = {}
```
Reason: Assigning a new table is generally faster because it avoids traversing and nil-ing every existing entry; use table.Empty(t) only when preserving the table’s identity matters.


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

if allowed[value] then
    print("Value exists")
end
```
Reason: A keyed set uses near-constant-time lookup, while table.HasValue scans the list linearly.


```lua
local playerData = {
    name = "Alyx",
    health = 100,
    alive = true
}
```
Reason: The constructor lets Lua allocate and populate the table in one operation, avoiding separate field assignments.


```lua
local items = { "a", "b", "c" }
local item = items[math.random(#items)]
```
Reason: Sequential tables support direct random indexing, avoiding the key-selection overhead of `table.Random`; the table must be non-empty.


```lua
local squared = x * x
```
Reason: Multiplication avoids the overhead of a function call and is the fastest, idiomatic way to square a number in a tight loop.


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


```lua
for _, ent in ents.Iterator("prop_physics") do
    -- Process ent here.
end
```
Reason: ents.Iterator("prop_physics") lazily visits matching entities without building a table of them.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid safely rejects nil, NULL, and removed entities before method calls.


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


```lua
-- Reuse Garry's Mod's cached zero Angle.
local zeroAngle = angle_zero

-- Hot path: treat zeroAngle as read-only.
UseAngle(zeroAngle)
```
Reason: `angle_zero` avoids the per-call allocation and constructor overhead of `Angle()`; use a separate reusable scratch Angle if the value must be mutated.


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

local color = ADDON_COLOR
```
Reason: A local avoids global and nested-table lookups, making it fastest for frequent reads.


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

-- Avoid using the replicated implementation detail directly:
local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is DarkRP’s intended accessor, while `GetNWString("job")` depends on an internal networking detail.


```lua
local threshold = 100

if firstVector:DistToSqr(secondVector) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: `DistToSqr` avoids the square-root cost of calculating the actual distance.


```lua
for _, ent in ents.Iterator() do
    -- Process ent here.
end
```
Reason: `ents.Iterator()` traverses entities without allocating the full table produced by `ents.GetAll()`, making it more efficient for direct iteration.


```lua
local function EntitiesNearPlayer(ply, radius)
    local pos = ply:GetPos()
    local extent = Vector(radius, radius, radius)

    return ents.FindInBox(pos - extent, pos + extent)
end
```
Reason: `ents.FindInBox` is a fast built-in broad-phase query; use the returned AABB candidates directly or distance-filter them when a true radius is required.


```lua
local function PlayersWithinRadius(origin, radius)
    local radiusSqr = radius * radius
    local nearby = {}

    for _, ply in player.Iterator() do
        if origin:DistToSqr(ply:GetPos()) <= radiusSqr then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```
Reason: Iterates only active players, avoids scanning unrelated entities and player-type checks, and uses squared distance without a square root.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` loops use Lua’s specialized counting-loop machinery and are generally faster than manually checking and incrementing a `while` loop.


```lua
hook.Add("Think", "NotifyAllPlayers", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)

hook.Add("CustomPlayerTick", "RunPlayerLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Custom logic for ply.
    end
end)
```
Reason: One hook dispatch and argument setup per tick; the per-player loop runs inside the handler instead of paying hook.Run overhead for every player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache the health value once per frame instead of calling LocalPlayer():Health() three times.


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

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

    for i = 1, #self.items do
        local item = self.items[i]
        surface.DrawRect(item.x, item.y, item.w, item.h)
    end
end
```
Reason: Create the immutable color once and set the draw color outside the loop, avoiding repeated allocation and state updates.


```lua
local sin = math.sin
local total = 0

for i = 1, 1000000 do
    total = total + sin(i)
end
```
Reason: A local lookup avoids repeatedly indexing the global `math` table for `math.sin`.


```lua
local cachedPlayer

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

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

    -- Reuse ply throughout this hot path.
    local position = ply:GetPos()
    local alive = ply:Alive()
end)
```
Reason: Cache the player entity once after client initialization, then reuse the local reference instead of repeatedly calling the global LocalPlayer() lookup.


```lua
local function AreLookingAtEachOther(a, b, minDot)
    minDot = minDot or 0.75

    local delta = b:EyePos() - a:EyePos()
    if delta:LengthSqr() == 0 then return false end

    local toB = delta:GetNormalized()
    return a:GetAimVector():Dot(toB) >= minDot
       and b:GetAimVector():Dot(-toB) >= minDot
end
```
Reason: Dot products compare each normalized aim vector against the other player’s direction without the cost of `math.acos`; `0.75` gives a roughly 41° facing cone.


```lua
SomeHelper(ply)
```
Reason: The direct call is generally faster because colon syntax performs a method lookup on `ply` before passing it as the implicit first argument.


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


```lua
for i = 1, #values do
    local value = values[i]
    -- process value
end
```
Reason: A numeric `for` with direct indexing typically has less iterator overhead than `pairs` or `ipairs` for dense sequential arrays.


```lua
-- Equivalent to Filter(admin players) followed by Map(player names).
local players = player.GetAll()
local adminNames = {}
local nameCount = 0

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

    if IsValid(ply) and ply:IsAdmin() then
        nameCount = nameCount + 1
        adminNames[nameCount] = ply:Nick()
    end
end
```
Reason: One pass avoids the intermediate filtered table and per-item combinator dispatch.


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

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

local function addCachedPlayer(ply)
    if playerSlot[ply] ~= nil then
        return
    end

    local slot = #cachedPlayers + 1
    cachedPlayers[slot] = ply
    playerSlot[ply] = slot
end

local function removeCachedPlayer(ply)
    local slot = playerSlot[ply]
    if slot == nil then
        return
    end

    local lastSlot = #cachedPlayers
    local lastPlayer = cachedPlayers[lastSlot]

    cachedPlayers[slot] = lastPlayer
    cachedPlayers[lastSlot] = nil
    playerSlot[lastPlayer] = slot
    playerSlot[ply] = nil
end

hook.Add("PlayerInitialSpawn", "CachePlayers", addCachedPlayer)
hook.Add("PlayerDisconnected", "CachePlayers", removeCachedPlayer)

hook.Add("Think", "ProcessCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Per-tick work for ply goes here.
    end
end)
```
Reason: The tick hook reuses one array; player cache updates happen only on startup, join, and disconnect.


```lua
local tempByPlayer = {}

local function setTemp(ply, value)
    tempByPlayer[ply] = value
end

hook.Add("PlayerDisconnected", "ClearTempData", function(ply)
    tempByPlayer[ply] = nil
end)

setTemp(ply, value)

-- Hot read path:
local value = tempByPlayer[ply]
```
Reason: A local Lua table lookup avoids the Garry's Mod entity field/metatable lookup used by `ply.someField`, while explicit cleanup prevents stale player references.


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

local count = #values
for i = 1, count do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays use contiguous numeric storage and are faster to iterate than string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing numeric channels avoids Color object overhead in the hot draw path.


```lua
local rows = sql.Query("SELECT points FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
```
Reason: Local SQLite typically has lower latency because it avoids remote network round trips and connection overhead; MySQL is mainly useful for shared multi-server data.


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

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

-- Hot path:
local steamID = CachedSteamID(ply)
```
Reason: The first lookup calls `SteamID()` once per player; later calls use a table lookup, while weak keys avoid retaining disconnected player objects.


```lua
local pieces = {}

for i = 1, thousands do
    pieces[i] = make_piece(i)
end

local result = table.concat(pieces)
```
Reason: `table.concat` joins the pieces efficiently in one operation, avoiding repeated intermediate string allocations from `..`.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws directly without the rounded-box wrapper and its radius handling.


```lua
local FONT = "DermaDefault"
local TEXT = "Status: OK"
local X, Y = 32, 32

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(FONT)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(X, Y)
    surface.DrawText(TEXT)
end)
```
Reason: Direct surface calls avoid draw.* wrapper and alignment work, while SimpleTextOutlined performs multiple extra draw passes.


```lua
local length = #myTable
```
Reason: The `#` operator is idiomatic and efficient for sequential array-like tables; `table.Count` is unnecessary.


```lua
t = {}
```
Reason: `t = {}` replaces the table reference in constant time, while `table.Empty(t)` removes entries one by one; use `table.Empty(t)` only when existing references must see the same table emptied.


```lua
local allowedClasses = {
    prop_physics = true,
    prop_dynamic = true,
    npc_citizen = true,
}

if allowedClasses[className] then
    -- Value exists in the set.
end
```
Reason: Set-style table lookup is average O(1), while table.HasValue scans a list linearly in O(n).


```lua
local playerData = {
    name = "Alyx",
    score = 0,
    alive = true
}
```
Reason: The constructor initializes known fields during table creation, avoiding separate post-creation assignments.


```lua
local function randomSequential(tbl)
    return tbl[math.random(1, #tbl)]
end

local value = randomSequential(myTable)
```
Reason: Direct numeric indexing avoids table.Random's key collection and lookup overhead for sequential tables.


```lua
local squared = x * x
```
Reason: Multiplication is faster and more direct than exponentiation for squaring.


```lua
for _, ply in player.Iterator() do
    -- Visit ply here.
end
```
Reason: player.Iterator() visits all currently connected players without allocating the table returned by player.GetAll().


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, so filtering by class avoids allocating a table of all map entities.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a function to run when the `Think` hook fires, keyed by the identifier `MyAddon.Think`.


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid(ent)` checks that the reference is a valid, non-NULL entity before calling entity methods.


```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.


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

-- Hot path: returns a fresh zeroed Angle without calling the global constructor.
local function FreshZeroAngle()
    return ZERO_ANGLE * 1
end

-- Slower in tight loops:
-- local a = Angle()
```
Reason: Copying a cached zero Angle with scalar multiplication avoids the repeated constructor call while still returning a new mutable Angle.


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

local color = configColor
```
Reason: A local flat variable is fastest because it avoids global/table lookups, while `myaddon.config.color` performs multiple table indexing operations per read.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: DarkRP stores a player's job as their team, so `team.GetName(ply:Team())` is the direct server-side API; `ply:GetNWString("job")` is networked string access and is slower/staler than reading the team.


```lua
if a:DistToSqr(b) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root used by distance methods, so it is preferred for threshold checks.


```lua
for ent in ents.Iterator() do
    -- Visit ent here.
end
```
Reason: `ents.Iterator()` walks every entity without building the table that `ents.GetAll()` returns, so it is the preferred efficient iterator when you only need to visit each entity once.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if ent ~= ply and ent:IsValid() then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for nearby entities around a point, and common benchmarks usually place it among the cheaper `FindIn*` choices without relying on PVS visibility.


```lua
local function FindPlayersInRadius(origin, radius)
    local radiusSqr = radius * radius
    local found = {}

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

    return found
end
```
Reason: Iterating `player.GetAll()` checks only players and uses squared distance, avoiding the broad entity search and player filtering cost of `ents.FindInSphere`.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are generally faster in Lua because the VM handles the counter, limit, and step directly with specialized loop opcodes, avoiding the extra manual condition and increment work of a while loop.


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

hook.Add("MyPlayerTickBatch", "ProcessPlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom per-player logic here
    end
end)
```
Reason: Running one hook dispatch per tick avoids paying hook lookup and callback dispatch overhead once per player.


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

draw.SimpleText(health, "HudFont", 24, 24, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.SimpleText(health .. "%", "HudFontSmall", 24, 48, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
draw.RoundedBox(4, 24, 72, math.max(0, health) * 2, 12, Color(200, 40, 40))
```
Reason: Cache `LocalPlayer()` and `Health()` once per `HUDPaint` frame so the draw code avoids repeated player lookup and method calls.


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

hook.Add("HUDPaint", "FastPaintColor", function()
    for _, item in ipairs(items) do
        surface.SetDrawColor(white)
        -- draw item here
    end
end)
```
Reason: `Color()` allocates a table, so creating it once outside the paint loop avoids per-frame per-item allocation work.


```lua
local sin = math.sin

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


```lua
local cachedLocalPlayer

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

    return cachedLocalPlayer
end

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

    -- Use ply here instead of calling LocalPlayer() repeatedly.
end)
```
Reason: Cache the player entity and refresh it only when invalid, so hot paths avoid repeated global LocalPlayer() lookups.


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

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

    local aimA = plyA:GetAimVector()
    local aimB = plyB:GetAimVector()

    return aimA:Dot(aimB) <= FACING_DOT
end
```
Reason: Dot product compares normalized aim directions without `math.acos`, so it avoids angle conversion and uses one cheap threshold check.


```lua
SomeHelper(ply)
```
Reason: Usually faster, because `ply:SomeHelper()` performs method lookup and passes `self`, while a local/free helper call can avoid the metatable-style lookup when you control the helper.


```lua
MsgC(Color(120, 200, 255), "debug value: ", tostring(value), "\n")
```
Reason: MsgC writes directly to the console and avoids the extra formatting/spacing behavior of print, so it is cheaper in a hot path.


```lua
for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: A numeric for loop avoids the iterator overhead of pairs/ipairs and is typically fastest for dense sequential array-like tables in Garry's Mod Lua.


```lua
local function activeNamesByJob(players, job)
    local out = {}
    local n = 0

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

    return out
end
```
Reason: One plain numeric loop fuses filter and map into a single pass, avoiding fn closure calls, intermediate tables, iterator overhead, and repeated table growth work.


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

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

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

hook.Add("Think", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Per-player tick work here.
        end
    end
end)
```
Reason: `player.GetAll()` allocates/builds a player list, so doing it only on join/leave avoids repeated per-tick table work while keeping iteration fast.


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

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

local function GetTemp(ply)
    return tempData[ply]
end
```
Reason: A side table keyed by player avoids player Entity metatable/index lookup overhead on hot reads, while weak keys let entries disappear after the player object is no longer referenced.


```lua
local values = { "alpha", "bravo", "charlie" }

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays iterate faster because Lua can walk the array part directly, while string-keyed maps require hash-table traversal.


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

hook.Add("HUDPaint", "FastDrawColorExample", function()
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(16, 16, 128, 32)
end)
```
Reason: Passing cached numeric channels avoids creating or unpacking a Color object in the hot draw path.


```lua
local steamId = "76561198000000000"
local row = sql.QueryRow("SELECT coins FROM player_data WHERE steam_id = " .. sql.SQLStr(steamId) .. " LIMIT 1")
```
Reason: Local SQLite avoids network round trips, so for one server with no sync need it is typically lower latency than remote MySQL.


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

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

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

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

-- Hot path example:
for _, ply in ipairs(player.GetHumans()) do
    local steamId = cachedSteamID(ply)
    -- use steamId here
end
```
Reason: Cache by Player object with weak keys so repeated hot-path lookups avoid repeated SteamID calls while disconnected players can be collected.


```lua
local parts = {}

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

local result = table.concat(parts)
```
Reason: `table.concat` builds the final string in one pass, while repeated `..` copies the growing string over and over.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` still goes through the rounded-box helper path, while `surface.DrawRect` draws the plain rectangle directly after setting the color.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: Direct `surface.*` calls avoid the extra wrapping, alignment, newline handling, and outline work in `draw.DrawText` / `draw.SimpleTextOutlined`, so they are faster for one single-line string drawn every frame.


```lua
local count = #items
```
Reason: The `#` length operator is the preferred way to get the length of a sequential array-like Lua table.


```lua
t = {}
```
Reason: Replacing the table avoids clearing each existing key, so it is generally faster when no other references need to keep using the same table.


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

if allowed[userGroup] then
    -- value exists in the set
end
```
Reason: A keyed set does one hash lookup, while table.HasValue scans the list linearly.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: A table constructor fills known fields during creation, avoiding separate field assignment bytecode and extra hash insert steps after `{}`.


```lua
local value = list[math.random(#list)]
```
Reason: For a sequential table, direct numeric indexing avoids table.Random's generic key iteration overhead.


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


The recommendation changes the set of visited players.

```lua
for _, ply in ipairs(player.GetHumans()) do
    -- ...
end
```
Reason: `ipairs` iterates the sequential player array directly, and `player.GetHumans()` visits currently connected human players.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, so filtering by class inside the loop avoids `ents.FindByClass`/`ents.GetAll` table allocation.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid` checks that the value is a valid entity/panel and has not become NULL or removed before you call methods on it.


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


```lua
-- Slower in a hot path: allocates a new Angle userdata every call.
local function slow()
    local ang = Angle()
    return ang
end

-- Faster: keep a scratch Angle and reset it before each use.
local scratchAng = Angle()

local function fast()
    scratchAng:Zero()
    return scratchAng
end
```
Reason: Reusing one Angle avoids repeated userdata allocation and constructor overhead; only copy it if the caller stores or mutates it later.


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

local color = addonColor
```
Reason: A local variable read avoids repeated table indexing, so it is faster than `myaddon.config.color` on a hot path.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred DarkRP API
-- local jobName = ply:GetNWString("job") -- avoid direct NWString access
```
Reason: DarkRP owns and synchronizes job data through DarkRPVars, so `getDarkRPVar("job")` matches the framework contract.


```lua
local maxDistance = 250

if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root used by real distance calculation, so it is preferred for threshold checks.


Answer must contain 1 through 1 candidate loops.

```lua
if ents.Iterator then
    for _, ent in ents.Iterator() do
        -- Visit ent here.
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- Visit ent here.
    end
end
```
Reason: ents.Iterator avoids allocating the ents.GetAll table on Garry's Mod versions that provide it, while the fallback preserves compatibility.


```lua
local radius = 512
local origin = ply:GetPos()

for _, ent in ipairs(ents.FindInSphere(origin, radius)) do
    if IsValid(ent) and ent ~= ply then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` uses the engine's spatial partition for a bounded radius query, making it a cheap built-in choice for nearby entities without defaulting to `FindInPVS`.


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

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

    return found
end
```
Reason: `player.GetAll()` scans only players and `DistToSqr` avoids square roots, so it skips the broader entity sphere query and player filtering cost.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric for is generally faster for simple 1..n counting because Lua handles the counter, limit, and step in the loop opcode instead of doing explicit condition checks and increments in Lua code.


Answer must contain 0 through 1 candidate loops.

```lua
-- Faster: one hook dispatch per tick, listeners loop the player list if needed.
hook.Add("Tick", "NotifyPlayersOnce", function()
    hook.Run("CustomThinkForPlayers", player.GetAll())
end)

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

-- Slower: N hook dispatches per tick.
hook.Add("Tick", "NotifyPlayersIndividually", function()
    local players = player.GetAll()
    for i = 1, #players do
        hook.Run("CustomThinkForPlayer", players[i])
    end
end)
```
Reason: `hook.Run` has dispatch overhead, so doing it once per tick and passing the player array avoids paying that overhead once for every player.


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

    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 20, color_white)
    draw.RoundedBox(4, 20, 45, health * 2, 18, Color(220, 40, 40))
    draw.SimpleText(health .. "%", "DermaDefault", 30, 46, color_white)
end)
```
Reason: Cache `LocalPlayer():Health()` once per frame so the draw code avoids repeated player lookup and method calls while using the same value consistently.


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

hook.Add("HUDPaint", "FastPaintExample", function()
    for _, item in ipairs(items) do
        draw.SimpleText(item.text, "DermaDefault", item.x, item.y, WHITE)
    end
end)
```
Reason: `Color()` allocates a color table, so creating it once outside the paint loop avoids per-frame/per-item allocation work.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

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

    return localPlayer
end

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

    -- Use ply instead of calling LocalPlayer() repeatedly here.
end)
```
Reason: Cache the player after it exists, then refresh only when invalid so hot paths avoid repeated global `LocalPlayer()` lookups.


```lua
local FACE_DOT = -0.75 -- lower is stricter; -1 means perfectly opposite aim directions

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

    return plyA:GetAimVector():Dot(plyB:GetAimVector()) <= FACE_DOT
end
```
Reason: A dot product compares aim direction alignment without `math.acos`; opposite-facing aim vectors approach `-1`, so a threshold gives a cheap rough check.


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

SomeHelper(ply)
```
Reason: Generally faster, because a local function call avoids the per-call method lookup/metatable path used by `ply:SomeHelper()`.


```lua
Msg("debug: hot path reached\n")
```
Reason: `Msg` writes directly to the console and avoids the extra formatting/newline work that `print` does.


```lua
for i = 1, #nums do
    local value = nums[i]
    -- use value
end
```
Reason: A numeric `for` loop avoids the iterator overhead of `pairs`/`ipairs` and is typically fastest for large sequential array-like tables in Garry's Mod Lua.


```lua
-- Instead of DarkRP fn.filter(fn.compose(...)) / fn.map(...), fuse the passes.
local function collectAffordableGunNames(shipments, ply, maxPrice)
    local out, n = {}, 0

    for i = 1, #shipments do
        local shipment = shipments[i]
        local price = shipment.price or 0

        if price <= maxPrice and (not shipment.allowed or table.HasValue(shipment.allowed, ply:Team())) then
            n = n + 1
            out[n] = shipment.name
        end
    end

    return out
end

local names = collectAffordableGunNames(CustomShipments, LocalPlayer(), 5000)
```
Reason: A single plain Lua loop avoids fn's extra closures, iterator/combinator calls, intermediate tables, and multiple passes while doing the same filter/map work.


```lua
local cachedPlayers = {}

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

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

RefreshPlayerCache()

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

        if IsValid(ply) then
            -- Per-player tick work here.
        end
    end
end)
```
Reason: `player.GetAll()` allocates/builds a player list, so caching it and refreshing only on join/leave removes that per-tick cost while keeping the hot loop numeric and cheap.


```lua
local tempByPlayer = {}

hook.Add("PlayerDisconnected", "ClearTempByPlayer", function(ply)
    tempByPlayer[ply] = nil
end)

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

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

-- hot path
hook.Add("Think", "ReadTempOften", function()
    for _, ply in ipairs(player.GetAll()) do
        local value = tempByPlayer[ply]
        if value then
            -- use value
        end
    end
end)
```
Reason: A local upvalue table keyed by the Player object avoids repeated Entity table/metatable field lookup, so `tempByPlayer[ply]` is typically faster to read than `ply.someField`.


```lua
local values = { "alpha", "bravo", "charlie", "delta" }

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because numeric indexing with a fixed `for` loop avoids hash-key traversal overhead.


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

hook.Add("HUDPaint", "FastDrawColorExample", function()
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(32, 32, 160, 24)
end)
```
Reason: Passing cached numeric channels avoids allocating or unpacking a Color object on every hot draw call.


```lua
local steamID = sql.SQLStr(ply:SteamID64())
local row = sql.QueryRow("SELECT money, xp FROM player_data WHERE steam_id = " .. steamID .. " LIMIT 1")
```
Reason: Local SQLite via GMod's `sql` library is typically lower latency because it avoids network round trips to a remote MySQL server for a single-server, no-sync setup.


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

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

    if not IsValid(ply) then
        return nil
    end

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

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

-- Hot path example:
-- local steamID = FastSteamID(ply)
```
Reason: `ply:SteamID()` is paid once per player object, then reused from a weak-key cache that does not keep disconnected players alive.


```lua
local parts = {}

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

local result = table.concat(parts)
```
Reason: `table.concat` builds the final string in one pass, while repeated `..` concatenation repeatedly allocates and copies growing intermediate strings.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips the extra `draw.RoundedBox` wrapper/rounded-corner path, so it is slightly cheaper for plain rectangles.


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

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


```lua
local len = #items
```
Reason: `#` is the preferred constant-time length operator for sequential array-like tables; `table.Count` is for counting all key/value pairs.


```lua
t = {}
```
Reason: Replacing the table is generally faster because it avoids iterating over and niling every existing element, assuming no other code needs the same table reference emptied in place.


```lua
local allowed = {
    admin = true,
    moderator = true,
    trusted = true,
}

if allowed[playerRank] then
    -- value exists in the set
end
```
Reason: A keyed set does an O(1) hash lookup, while table.HasValue scans the list O(n).


```lua
local playerInfo = {
    name = ply:Nick(),
    health = ply:Health(),
    armor = ply:Armor(),
}
```
Reason: The table constructor fills known fields during allocation, avoiding separate hash assignments after creating an empty table.


```lua
local function RandomSequential(tbl)
    return tbl[math.random(#tbl)]
end
```
Reason: For sequential arrays, direct numeric indexing avoids `table.Random`'s generic table traversal.


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


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


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities without allocating the full `ents.GetAll()` table, and the class check limits work to `prop_physics`.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers a callback on the Think hook with the identifier MyAddon.Think.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` safely rejects `nil`, `NULL`, and removed entities before method calls.


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


```lua
local ZERO_ANGLE = angle_zero

-- In the hot path, do not allocate with Angle() when a read-only zero angle is enough.
local function useZeroAngle()
    local ang = ZERO_ANGLE
    -- use ang without mutating it
end
```
Reason: Reusing Garry's Mod's cached `angle_zero` avoids per-call `Angle()` userdata allocation; only construct a new `Angle()` when the caller will mutate or store it.


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

surface.SetDrawColor(configColor)
```
Reason: A local/upvalue read avoids repeated table indexing, while `myaddon.config.color` performs multiple table lookups each read.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP owns the job value through DarkRPVars, so `getDarkRPVar("job")` uses the correct cached DarkRP API instead of raw `GetNWString("job")` access.


```lua
local maxDistance = 500

if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root used by distance checks when you only need a threshold comparison.


```lua
local function VisitEntity(ent)
    -- Do per-entity work here.
end

if ents.Iterator then
    for ent in ents.Iterator() do
        VisitEntity(ent)
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        VisitEntity(ent)
    end
end
```
Reason: `ents.Iterator()` avoids building the `ents.GetAll()` table for a simple full-entity scan, with `ents.GetAll()` kept as a compatibility fallback.


```lua
local function ForEntitiesNearPlayer(ply, radius, fn)
    local origin = ply:GetPos()
    local extent = Vector(radius, radius, radius)
    local radiusSqr = radius * radius

    for _, ent in ipairs(ents.FindInBox(origin - extent, origin + extent)) do
        if ent ~= ply and ent:GetPos():DistToSqr(origin) <= radiusSqr then
            fn(ent)
        end
    end
end
```
Reason: `ents.FindInBox` is a fast built-in broad-phase query in common GMod benchmarks, and the squared-distance filter keeps exact radius behavior without using `FindInPVS`.


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

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

    return found
end
```
Reason: This scans only players and uses squared distance, avoiding the broad entity query, player filtering, and square-root distance cost from `ents.FindInSphere`.


```lua
for i = 1, n do
    -- tight loop body
end
```
Reason: Numeric for is generally faster because Lua handles the counter, limit, and step in optimized loop bytecode instead of doing explicit while-condition and increment work in Lua.


```lua
-- Faster: one hook dispatch per tick, listeners loop the player list if needed.
hook.Add("Tick", "NotifyPlayersOnce", function()
    hook.Run("CustomLogicForPlayers", player.GetAll())
end)

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

-- Slower pattern: pays hook dispatch overhead once per player per tick.
-- hook.Add("Tick", "NotifyPlayersMany", function()
--     local players = player.GetAll()
--     for i = 1, #players do
--         hook.Run("CustomLogicForPlayer", players[i])
--     end
-- end)
```
Reason: `hook.Run` has dispatch overhead, so calling it once per tick with the player array avoids repeating that overhead for every player.


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

    draw.SimpleText("Health: " .. health, "DermaDefault", 24, 24, color_white)
    draw.RoundedBox(4, 24, 46, math.Clamp(health, 0, 100) * 2, 12, Color(220, 60, 60))
    draw.SimpleText(health .. "%", "DermaDefault", 24, 64, color_white)
end)
```
Reason: `LocalPlayer()` and `:Health()` are each resolved once per HUDPaint frame, then the cached `health` value is reused by all three draw calls.


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

hook.Add("HUDPaint", "FastPaintLoop", function()
    for _, item in ipairs(items) do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(item.x, item.y, item.w, item.h)
    end
end)
```
Reason: Create the Color object once outside the paint loop, avoiding a table allocation and constructor call every iteration.


```lua
local sin = math.sin

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


```lua
local cachedLocalPlayer

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

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

    return cachedLocalPlayer
end

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

    -- hot-path client code here
    local pos = ply:GetPos()
end)
```
Reason: Cache the player entity in a local upvalue after it exists, then reuse that reference so hot paths avoid repeated global LocalPlayer lookups and full engine calls except when the cache is invalid.


```lua
local LOOK_DOT = 0.75 -- about a 41 degree cone; raise for stricter checks

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

    local aPos = a:EyePos()
    local bPos = b:EyePos()
    local toB = bPos - aPos

    local distSqr = toB:LengthSqr()
    if distSqr <= 0 then return false end

    toB:Normalize()

    return a:GetAimVector():Dot(toB) >= LOOK_DOT
        and b:GetAimVector():Dot(-toB) >= LOOK_DOT
end
```
Reason: Dot products compare facing direction against a threshold without `math.acos`, avoiding expensive angle conversion while still giving a tunable rough look cone.


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

SomeHelper(ply)
```
Reason: Usually faster, because a local function call avoids the `ply.SomeHelper`/metatable method lookup that `ply:SomeHelper()` performs before passing `ply` as `self`.


```lua
Msg("[debug] hot path reached\n")
```
Reason: `Msg` writes directly to the console and avoids `print`'s extra argument formatting; include the newline yourself.


```lua
local nums = largeSequentialTable

for i = 1, #nums do
    local value = nums[i]
    -- use value
end
```
Reason: A numeric `for` over `1, #table` avoids iterator function overhead from `pairs`/`ipairs` and is typically fastest for large sequential array-like tables.


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

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

        if IsValid(ply) and ply:Team() == TEAM_CITIZEN and ply:isWanted() then
            n = n + 1
            out[n] = ply:Nick()
        end
    end

    return out
end

local names = getWantedCitizenNames(player.GetAll())
```
Reason: This fuses filter and map into one numeric loop, avoiding DarkRP fn closure dispatch, chained iterator/combinator overhead, and intermediate tables.


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

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

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

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

        if IsValid(ply) then
            -- Do per-player tick work here.
        end
    end
end)
```
Reason: `player.GetAll()` allocates/builds a table each call, so keeping one compact cached array makes the hot Tick path only iterate existing players while join/leave hooks pay the update cost.


```lua
local scoreByPlayer = {}

local function SetTempScore(ply, value)
    scoreByPlayer[ply] = value
end

local function GetTempScore(ply)
    return scoreByPlayer[ply]
end

hook.Add("PlayerDisconnected", "ClearTempScore", function(ply)
    scoreByPlayer[ply] = nil
end)
```
Reason: A local Lua table keyed by the player avoids repeated entity field/metatable lookup, so hot reads are cheaper than `ply.someField`.


```lua
-- Slower shape for frequent full iteration: hash part, string keys.
local byName = {
    idle = "idle",
    walk = "walk",
    run = "run",
}

for name, value in pairs(byName) do
    -- use value
end

-- Faster shape for frequent fixed-order iteration: array part, sequential number keys.
local sequence = {
    "idle",
    "walk",
    "run",
}

for i = 1, #sequence do
    local value = sequence[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays keep values in Lua's array part and allow a plain numeric loop, avoiding hash-key traversal from `pairs` over string-keyed maps.


```lua
-- Hot draw path: pass channels directly, not a Color object.
surface.SetDrawColor(255, 64, 32, 255)
```
Reason: Passing numeric channels avoids Color table/object handling on every draw call.


```lua
local steamID = sql.SQLStr(ply:SteamID64())
local row = sql.QueryRow("SELECT coins, xp FROM player_data WHERE steamid64 = " .. steamID .. " LIMIT 1")
```
Reason: Local SQLite is typically lower latency because it avoids remote MySQL network round trips, which matters more than multi-server sync when one game server owns the data.


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

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

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

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

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

-- Hot path:
local steamID = CachedSteamID(ply)
```
Reason: SteamID is stable for a connected player, so the hot path pays one table lookup instead of repeated engine method calls.


```lua
-- Slower: repeated concatenation copies the growing string each time.
local out = ""
for i = 1, #pieces do
    out = out .. pieces[i]
end

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

local outFast = table.concat(buffer)
```
Reason: `table.concat` performs one final join instead of repeatedly reallocating and copying an ever-growing string.