```lua
local localPlayer

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

-- Hot paths: use localPlayer instead of calling LocalPlayer().
hook.Add("HUDPaint", "Example", function()
    if not IsValid(localPlayer) then return end
    local health = localPlayer:Health()
end)
```
Reason: `InitPostEntity` runs once the client player entity exists, so hot paths reuse the cached entity instead of repeatedly resolving `LocalPlayer()`.


```lua
local function RoughlyLookingAtEachOther(a, b)
    return a:GetAimVector():Dot(b:GetAimVector()) <= -0.5
end
```
Reason: Aim vectors are normalized, so their dot product is cheap to compute and becomes negative when they point roughly opposite directions; no math.acos is needed.


```lua
SomeHelper(ply)
```
Reason: Prefer a direct helper call; it avoids the player/metatable method lookup, while `:` only adds `ply` as the first argument.


```lua
MsgN("debug line")
```
Reason: MsgN writes a single console string with its newline, avoiding print's generic argument handling.


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


```lua
-- Equivalent result to: fn.Map(toName, fn.Filter(isEligible, players))
local function eligiblePlayerNames(players)
    local names = {}
    local count = 0

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

    return names
end

local names = eligiblePlayerNames(player.GetAll())
```
Reason: One indexed, fused loop preserves order while avoiding combinator calls, iterator overhead, and the intermediate filtered table.


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

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

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

hook.Add("Tick", "MyAddon.ProcessPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Per-player tick work here.
    end
end)
```
Reason: `player.GetAll()` allocates/builds the player list only at startup and on join/leave events, not every tick.


```lua
local temporaryByPlayer = {}

temporaryByPlayer[ply] = value

-- Hot-path read:
local value = temporaryByPlayer[ply]

hook.Add("PlayerDisconnected", "clear_temporary_player_data", function(ply)
    temporaryByPlayer[ply] = nil
end)
```
Reason: A plain Lua table keyed by the player avoids the Entity `__index` lookup used by `ply.someField` and makes the hot read a direct table lookup.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential integer keys use Lua’s array storage, and a numeric loop avoids string-hash map traversal.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing numeric channels avoids the Color table/object handling on each hot-path call.


```lua
local coins = sql.QueryValue(
    "SELECT coins FROM player_data WHERE steamid = " .. sql.SQLStr(steamID)
)
```
Reason: Local SQLite avoids network round trips, so it typically has lower read/write latency on 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

-- Hot path
local steamID = CachedSteamID(ply)
```
Reason: The SteamID is fetched from Garry's Mod once per player, then subsequent calls use a cheap Lua table lookup; weak keys avoid retaining disconnected players.


Answer must contain 0 through 0 candidate loops.

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

-- Fast: collect pieces, then concatenate once.
local output = table.concat(pieces)
```
Reason: `table.concat` avoids repeatedly reallocating and copying the ever-growing string.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, width, height)
```
Reason: Direct surface calls avoid draw.RoundedBox's wrapper overhead when no rounded corners are needed.


```lua
hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText("Hello, world!")
end)
```
Reason: Direct `surface.DrawText` avoids the alignment, multiline, and outline work performed by higher-level `draw.DrawText` and `draw.SimpleTextOutlined` helpers.


```lua
local length = #myTable
```
Reason: The `#` operator is the standard way to get a sequential table's length.


```lua
t = {}
```
Reason: Replacing the table is generally O(1), while `table.Empty(t)` iterates over and removes every existing entry; use `table.Empty` only when other code must keep the same table reference.


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

if allowed[role] then
    -- value exists
end
```
Reason: Hash-table lookup is average O(1), while `table.HasValue` scans a list in O(n).


```lua
local state = {
    health = health,
    armor = armor,
    alive = alive,
}
```
Reason: A table constructor lets LuaJIT pre-size the known fields, avoiding growth work from assigning them after `{}`.


```lua
local value = items[math.random(#items)]
```
Reason: A sequential table has contiguous numeric indices, so direct random indexing avoids table.Random's extra table handling.


```lua
local squared = x * x
```
Reason: Direct multiplication is the fastest, allocation-free square operation in Lua.


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` yields matching entities one at a time without first building a table of them.


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


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the entity is non-nil and has not been removed 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 the named incoming net message.


```lua
-- Reuse a zeroed Angle instead of allocating a new one each time.
local ZERO_ANGLE = Angle(0, 0, 0)

-- Hot path:
local angle = ZERO_ANGLE
```
Reason: Reusing a shared zeroed Angle avoids repeated Angle() allocations and is faster in hot paths when the value is read-only; clone it before mutation.


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

local color = configColor
```
Reason: A local variable avoids repeated table indexing and global-environment lookup, making frequent reads faster.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: DarkRP jobs are represented by the player's team, so `team.GetName(ply:Team())` is preferred over the networked-string lookup.


```lua
if vec1:DistToSqr(vec2) <= 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()` visits entities efficiently without first creating a full entity table.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), radius)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for nearby entities and avoids the broader PVS semantics of `FindInPVS`.


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

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

    return nearby
end
```
Reason: It iterates only players and uses squared distance, avoiding ents.FindInSphere's broader entity search and the square-root cost of distance checks.


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


```lua
-- Faster: one hook dispatch per tick, with all players as an argument.
hook.Run("CustomPlayerTick", player.GetAll())

-- Slower: one hook dispatch for every player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("CustomPlayerTick", ply)
end
```
Reason: One `hook.Run` call avoids repeated hook lookup and dispatch overhead; process the player list inside the hook instead.


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

    draw.SimpleText(health, "Default", 20, 20, color_white)
    draw.SimpleText("HP: " .. health, "Default", 20, 40, color_white)
    draw.SimpleText(health > 0 and "Alive" or "Dead", "Default", 20, 60, color_white)
end)
```
Reason: Cache LocalPlayer():Health() once per frame and reuse the local value for all three draw calls.


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

hook.Add("HUDPaint", "Example", function()
    surface.SetDrawColor(white)
    -- paint using 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
-- Cache the player entity once and reuse it.
local ply = LocalPlayer()

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

    if IsValid(ply) then
        -- Use ply instead of calling LocalPlayer() repeatedly.
        local health = ply:Health()
    end
end)
```
Reason: Caching the player entity avoids repeated LocalPlayer() lookups while refreshing the cache if the entity becomes invalid.


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

    minDot = minDot or 0.7 -- smaller angle means stricter; 0.7 is roughly 45 degrees

    local delta = (plyB:GetPos() - plyA:GetPos()):GetNormalized()
    return plyA:GetAimVector():Dot(delta) >= minDot
       and plyB:GetAimVector():Dot(-delta) >= minDot
end
```
Reason: Normalize the direction between players once, then compare each aim vector with the facing direction using dot products, avoiding the expensive `math.acos` angle calculation.


```lua
SomeHelper(ply)
```
Reason: A direct function call avoids the colon call’s method lookup and implicit `self` setup, so it is generally faster when the helper is under your control.


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


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- process(value)
end
```
Reason: Numeric `for` typically has the lowest iteration overhead for dense sequential arrays; `pairs` is for key-value traversal, and `ipairs` adds iterator overhead.


```lua
-- fn.filter(allowed, function(ply) return ply:Alive() end)
--   :map(function(ply) return ply:Nick() end)
--   :filter(function(name) return name ~= "" end)

local names = {}
local count = 0

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

    if allowed[ply] and ply:Alive() then
        local name = ply:Nick()

        if name ~= "" then
            count = count + 1
            names[count] = name
        end
    end
end
```
Reason: One loop fuses the filter/map/filter stages, avoiding intermediate tables, iterator passes, and per-stage closure calls.


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

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

hook.Add("PlayerInitialSpawn", "RefreshPlayerCacheOnJoin", refreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", refreshPlayerCache)

hook.Add("Think", "ProcessCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- Per-tick player work here.
        end
    end
end)
```
Reason: `player.GetAll()` runs only when the player list changes, so the per-tick hook iterates the cached table instead of rebuilding it every tick.


```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 direct table lookup avoids repeated entity field lookup overhead, while weak keys allow disconnected player entities and their temporary data to be garbage-collected.


Answer must contain 0 through 1 candidate loops.

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

for i = 1, #values do
    local value = values[i]
end

-- String-keyed map: use for named lookup, not fastest sequential iteration
local colors = {
    first = "red",
    second = "green",
    third = "blue"
}

for key, value in pairs(colors) do
end
```
Reason: Sequential number-indexed arrays are faster for iteration because Garry's Mod Lua stores and traverses them in the array part, while string-keyed maps use hash lookups and `pairs` traversal.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate channel numbers avoids constructing or looking up a Color object in the hot draw path.


```lua
local result = sql.Query("SELECT value FROM player_data WHERE steamid = '...' LIMIT 1")
```
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 SteamID() results by player entity so repeated calls avoid native lookups while weak keys allow unused player entries 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 builds the final string once, avoiding repeated intermediate string allocations caused by .. concatenation.


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


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)

hook.Add("HUDPaint", "DrawFastText", function()
    surface.SetTextPos(32, 32)
    surface.DrawText("Hello, Garry's Mod!")
end)
```
Reason: `surface.DrawText` avoids the per-call setup and wrapper overhead used by `draw.DrawText`, `draw.SimpleText`, and `draw.SimpleTextOutlined`; cache the font and color outside the frame callback.


```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 when no existing references to t must be preserved:
t = {}

-- table.Empty(t) clears the existing table in place and is slower for large tables.
```
Reason: t = {} replaces the table reference in constant time, while table.Empty(t) must remove the existing entries one by one.


```lua
-- Faster: O(1) lookup in a set
local allowed = {
    crowbar = true,
    pistol = true,
    shotgun = true
}

if allowed[weaponClass] then
    print("Allowed")
end
```
Reason: A set uses direct key lookup, while table.HasValue scans the list linearly until it finds a match.


```lua
local player = {
    name = "Gordon",
    health = 100,
    alive = true,
}
```
Reason: A table constructor creates the known fields in one operation, avoiding separate assignments after allocation.


```lua
local value = items[math.random(#items)]
```
Reason: Sequential tables support direct indexed lookup, avoiding table.Random’s key enumeration overhead.


```lua
local squared = x * x
```
Reason: Multiplication is faster and more direct than calling a power function for squaring.


```lua
for ply in player.Iterator() do
    -- use ply here
end
```
Reason: `player.Iterator()` visits each currently connected player without creating an intermediate table.


```lua
for _, ent in ents.Iterator("prop_physics") do
    -- Visit ent here
end
```
Reason: ents.Iterator iterates entities lazily without first allocating a table containing them all.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the reference points to a valid, non-removed entity before method calls.


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


```lua
-- Use the shared zero angle when you only read from it.
local a = angle_zero
```
Reason: `angle_zero` avoids allocating and constructing a new Angle; do not mutate it, because it is shared.


```lua
local configColor = Color(255, 255, 255)
local currentColor = configColor
```
Reason: A local variable avoids repeated table lookups and is faster than nested or global access.


```lua
local job = ply:getDarkRPVar("job")
-- Avoid: ply:GetNWString("job")
```
Reason: DarkRP's `getDarkRPVar("job")` is the framework-owned API for the player's current job and avoids relying on a replicated networked-string implementation detail.


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


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


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 256)
for _, ent in ipairs(nearby) do
    -- Process nearby entities.
end
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for radius-based searches around a player, without relying on `FindInPVS`.


```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: Iterates only players and uses squared-distance checks, avoiding the broader entity spatial query, entity filtering, and square-root distance calculation.


```lua
for i = 1, n do
    -- work
end
```
Reason: A numeric `for` loop is generally faster than an equivalent `while` loop in Garry's Mod Lua because the runtime handles the counter update and termination with optimized loop operations.


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

hook.Add("CustomPlayerTick", "ProcessPlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Custom logic for ply
    end
end)
```
Reason: One hook dispatch per tick avoids repeating hook.Run lookup and dispatch overhead for every player while preserving one iteration over the player list.


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

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


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

hook.Add("HUDPaint", "Example", function()
    surface.SetDrawColor(white)
    -- Paint code here
end)
```
Reason: Create the Color object once and reuse it instead of allocating one 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 the hot loop.


```lua
local ply = LocalPlayer()

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

    if IsValid(ply) then
        -- Use ply instead of calling LocalPlayer() repeatedly.
        local health = ply:Health()
    end
end)
```
Reason: Cache the player reference and refresh it only when invalid, avoiding repeated LocalPlayer() lookups while handling initialization and respawn-related invalidation.


```lua
local function ArePlayersLookingAtEachOther(p1, p2, threshold)
    threshold = threshold or 0.5 -- 0.5 = within 60 degrees

    local delta = p2:EyePos() - p1:EyePos()
    local distance = delta:Length()
    if distance == 0 then return true end

    local toP2 = delta / distance
    local toP1 = -toP2

    return p1:GetAimVector():Dot(toP2) >= threshold
       and p2:GetAimVector():Dot(toP1) >= 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 local or upvalue helper call avoids the per-call `ply.SomeHelper` table lookup that colon syntax performs.


```lua
MsgN("debug line")
```
Reason: `MsgN` writes directly to the console with a newline and avoids `print`'s extra formatting and global output handling overhead.


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


```lua
-- Equivalent to: fn.Map(fn.Filter(players, isAlive), getName)
-- but with one pass and no intermediate list.
local names = {}
local count = 0

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

    if IsValid(player) and player:Alive() then
        count = count + 1
        names[count] = player:Nick()
    end
end
```
Reason: The fused loop performs filtering and mapping in one traversal, avoiding the intermediate tables, extra traversals, and function-call overhead created by chained fn combinators.


```lua
local cachedPlayers = {}

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

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

hook.Add("Think", "ProcessCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- Per-tick player logic here
        end
    end
end)
```
Reason: `player.GetAll()` runs only when the player list changes, so the Think hook iterates a cached table instead of rebuilding it every tick.


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

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

local function getTempData(ply)
    return playerData[ply]
end

setTempData(ply, value)
local value = getTempData(ply)
```
Reason: A local table keyed by the player uses a direct table lookup and avoids entity field lookup overhead; weak keys prevent temporary data from keeping player entities alive.


```lua
-- Faster: sequential number-indexed array
local values = { "alpha", "beta", "gamma" }

for i = 1, #values do
    local value = values[i]
end

-- Slower: string-keyed map
local map = {
    first = "alpha",
    second = "beta",
    third = "gamma"
}

for key, value in pairs(map) do
end
```
Reason: Sequential number-indexed arrays use optimized contiguous storage and faster numeric iteration, while string-keyed maps require hash lookups.


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


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = " .. 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
for _, ply in ipairs(players) do
    local steamID = CachedSteamID(ply)
    -- use steamID repeatedly here
end
```
Reason: SteamID() runs once per player, while the weak-key cache avoids retaining player entities after they are released.


```lua
local parts = {}

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

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


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, avoiding the extra rounded-box path and overhead of `draw.RoundedBox(0, ...)`.


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

local text = "Hello, Garry's Mod"
local font = "HUDText"

hook.Add("HUDPaint", "DrawFastText", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` avoids the per-call setup and wrapper overhead of `draw.DrawText` and `draw.SimpleTextOutlined`; cache the font and keep `surface.SetFont` outside the frame hook when the font never changes.


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


```lua
-- Generally faster when no other code needs the old table reference:
t = {}
```
Reason: t = {} replaces the table in constant time, while table.Empty(t) must remove its entries one by one; use table.Empty when existing references must remain valid.


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

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


```lua
local player = {
    name = "Gordon",
    health = 100,
    alive = true,
}
```
Reason: A table constructor initializes the known fields during creation, avoiding separate field-assignment operations after the table is allocated.


```lua
local value = items[math.random(#items)]
```
Reason: Sequential tables support direct index lookup, avoiding table.Random's general-purpose key iteration overhead.


```lua
local squared = x * x
```
Reason: Multiplication is faster and more direct than calling a power function in a tight loop.


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


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Handle ent here.
    end
end
```
Reason: ents.Iterator() visits entities lazily without first allocating a table containing every entity.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the reference points to a valid, non-removed entity before method calls.


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


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

-- Reuse this only within the hot-path operation; do not retain it across calls.
local function getZeroAngle()
    scratch:Zero()
    return scratch
end

local ang = getZeroAngle()
```
Reason: Reusing and zeroing one scratch Angle avoids a new allocation and constructor call; use a pool when callers must retain distinct Angle objects.


```lua
local addonColor = Color(255, 255, 255)
local currentColor = addonColor
```
Reason: A local variable avoids repeated table lookups and is faster to read frequently.


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

-- Avoid relying on the networked variable directly:
-- local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is DarkRP’s supported API and avoids coupling to its internal network-variable implementation.


```lua
if firstVector:DistToSqr(secondVector) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: DistToSqr avoids the unnecessary square-root calculation; compare it with the squared threshold.


```lua
for _, ent in ents.Iterator() do
    -- Visit ent here.
end
```
Reason: ents.Iterator() visits entities without first allocating the full table returned by ents.GetAll(), making it the efficient choice for a complete entity traversal.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 256)
for _, ent in ipairs(nearby) do
    -- Process ent
end
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for nearby entities without the visibility-oriented semantics of `FindInPVS`.


```lua
local function FindPlayersWithinRadius(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: It iterates only the player list and uses squared distance, avoiding the broader entity spatial query, entity filtering, and square-root distance calculation.


```lua
for i = 1, n do
    -- count from 1 to n
end
```
Reason: Lua’s numeric `for` loop is generally faster because iteration and counter updates are handled by the VM.


```lua
hook.Add("Think", "NotifyEveryPlayer", function()
    local players = player.GetAll()
    hook.Run("CustomPlayerTick", players)
end)

hook.Add("CustomPlayerTick", "HandlePlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Custom logic for ply
    end
end)
```
Reason: One hook dispatch replaces one dispatch per player, reducing repeated lookup and call overhead each tick.


```lua
hook.Add("HUDPaint", "DrawHealthHUD", function()
    local health = LocalPlayer():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 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)
    surface.DrawRect(0, 0, w, h)
end
```
Reason: Create the Color object once and reuse it instead of allocating one on every paint iteration.


```lua
local sin = math.sin

for i = 1, iterations do
    local value = sin(i)
    -- hot-loop work
end
```
Reason: Local lookup is typically faster than repeated table-field lookup through `math.sin`.


```lua
-- CLIENT
local cachedLocalPlayer

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

-- Use cachedLocalPlayer in hot paths after InitPostEntity.
if IsValid(cachedLocalPlayer) then
    cachedLocalPlayer:ChatPrint("Ready")
end
```
Reason: Cache the player entity once after client initialization and reuse the local variable instead of repeatedly calling LocalPlayer().


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

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

    local minDotSqr = threshold * threshold
    local dotA = a:GetAimVector():Dot(delta)
    local dotB = b:GetAimVector():Dot(-delta)

    return dotA > 0 and dotB > 0
        and dotA * dotA >= minDotSqr * distanceSqr
        and dotB * dotB >= minDotSqr * distanceSqr
end
```
Reason: Dot products test each aim vector against the direction to the other player, using squared comparisons to avoid `math.acos`, normalization, and extra square roots.


```lua
SomeHelper(ply)
```
Reason: It generally avoids the receiver method lookup; `ply:SomeHelper()` is equivalent to `ply.SomeHelper(ply)`.


```lua
MsgN("debug line")
```
Reason: `MsgN` writes directly to the console with a trailing newline and avoids `print`'s general-purpose argument handling, making it faster in hot paths.


```lua
local count = #numbers
for i = 1, count do
    local value = numbers[i]
    -- use value
end
```
Reason: Numeric `for` with a cached length typically has the least iterator and allocation overhead for dense sequential arrays; `ipairs` adds iterator overhead, while `pairs` is unordered and more general.


```lua
-- Combinator pipeline:
-- local result = fn.Map(function(ply) return ply:Nick() end,
--     fn.Filter(function(ply) return IsValid(ply) and ply:IsAdmin() end, player.GetAll()))

-- Fused filter + map: one pass, one result table, no intermediate list.
local result = {}
for _, ply in ipairs(player.GetAll()) do
    if IsValid(ply) and ply:IsAdmin() then
        result[#result + 1] = ply:Nick()
    end
end
```
Reason: The fused loop performs filtering and mapping in one traversal and avoids the intermediate table and extra function calls created by separate combinators.


```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
        -- Process ply here
    end
end)
```
Reason: `player.GetAll()` runs once initially and the cache changes only on player join or disconnect, so each tick iterates the existing cache directly.


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

tempByPlayer[ply] = value
local value = tempByPlayer[ply]
```
Reason: A local Lua table avoids entity-field lookup overhead, and weak keys let player entries disappear when the player object is collected.


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

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


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: Passing separate numbers avoids Color-object handling in the hot draw path.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = '...' LIMIT 1")
```
Reason: Local SQLite is typically lower latency because it avoids remote network round trips 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

for _, ply in ipairs(player.GetAll()) do
    local steamID = CachedSteamID(ply)
    -- Hot-path work using steamID...
end
```
Reason: It calls ply:SteamID() once per player, then reuses the cached string while weak keys allow discarded player objects to be garbage-collected.


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

-- Faster: collect pieces, then concatenate once.
local parts = {}
for _, piece in ipairs(pieces) do
    parts[#parts + 1] = piece
end
local result = table.concat(parts)
```
Reason: table.concat combines the pieces in one pass, avoiding repeated intermediate-string allocations from .. concatenation.


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


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

local text = "Status: ready"

hook.Add("HUDPaint", "DrawSingleLine", function()
    surface.SetFont("HUD_SingleLine")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` avoids the alignment, sizing, and repeated multi-pass work used by helpers; `SimpleTextOutlined` is slower because it draws the text multiple times.


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


```lua
t = {}
```
Reason: `t = {}` is generally faster because it replaces the reference without clearing each existing entry; use `table.Empty(t)` only when other references must see the same table emptied.


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

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


```lua
local playerData = {
    name = "Gordon",
    score = 100,
    alive = true,
}
```
Reason: A table constructor creates the table and populates its known fields in one operation, avoiding separate field-assignment steps.


```lua
local value = values[math.random(#values)]
```
Reason: Sequential tables support direct indexed lookup, avoiding the extra work table.Random performs to select and retrieve an element.


```lua
local squared = x * x
```
Reason: Multiplication avoids the overhead of calling `math.pow` in a tight loop.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- Handle ply here
end
```
Reason: `player.GetAll()` returns the currently connected players as an array, so `ipairs` visits each one.


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


```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 not NULL or removed before method calls.


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


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

-- Fast: allocate once, then reset and reuse it.
local scratchAngle = Angle()

local function fastZeroAngle()
    scratchAngle:Zero()
    return scratchAngle
end
```
Reason: `fastZeroAngle` avoids repeated userdata allocation; use it only when callers do not retain or concurrently mutate the returned Angle.


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

local color = ADDON_COLOR
```
Reason: A local variable avoids repeated table lookups and global-environment resolution.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred
-- Avoid: ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` uses DarkRP’s job data API; the generic NW string is not the authoritative interface.


```lua
if firstVector:DistToSqr(secondVector) <= threshold * threshold then
    -- Vectors are within range.
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()` visits all entities efficiently without first allocating the table returned by `ents.GetAll()`.


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

for _, ent in ipairs(ents.FindInBox(pos - bounds, pos + bounds)) do
    if ent ~= ply and IsValid(ent) then
        -- Handle nearby entity.
    end
end
```
Reason: `ents.FindInBox` is typically faster than sphere-based queries; use the box as a cheap candidate filter and apply an exact distance check only when needed.


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

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

    return nearby
end
```
Reason: Iterate only players and compare squared distances, avoiding the broader entity search, player-type filtering, square roots, and unnecessary distance calculations.


```lua
for i = 1, n do
    -- work
end
```
Reason: A numeric `for` uses a specialized counted-loop operation and is generally faster than manually incrementing a `while` loop.


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

hook.Add("CustomPlayerTick", "ProcessPlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Custom logic for ply.
    end
end)
```
Reason: One hook dispatch per tick avoids repeating hook lookup and callback-dispatch overhead for every player.


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

    local health = player:Health()

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(math.max(health, 0), "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache `LocalPlayer()` and `Health()` once per frame instead of recomputing them for every 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 instead of allocating a new one on every paint iteration.


```lua
local sin = math.sin

for i = 1, sampleCount do
    local value = sin(angle[i])
    -- process value
end
```
Reason: Cache `math.sin` in a local so each iteration avoids the table lookup.


```lua
local lp = LocalPlayer()

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

hook.Add("HUDPaint", "DrawPlayerInfo", function()
    if not IsValid(lp) then return end

    local health = lp:Health()
    -- Reuse lp throughout this hot path.
end)
```
Reason: Cache the player entity in a local upvalue and reuse it, avoiding repeated LocalPlayer() lookups.


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

    minDot = minDot or 0.8 -- about 37 degrees

    local p1ToP2 = (p2:EyePos() - p1:EyePos()):GetNormalized()
    local p2ToP1 = -p1ToP2

    return p1:GetAimVector():Dot(p1ToP2) >= minDot
       and p2:GetAimVector():Dot(p2ToP1) >= minDot
end
```
Reason: Dot products compare aim alignment directly against a cosine threshold, avoiding the slower `math.acos` angle calculation.


```lua
SomeHelper(ply)
```
Reason: Prefer a local/direct function call; `ply:SomeHelper()` performs method lookup and is generally no faster.


```lua
MsgN("[debug] value = ", value)
```
Reason: `MsgN` writes directly to the Garry's Mod console with a newline and avoids the extra overhead of Lua's `print` formatting.


```lua
for i = 1, #values do
    local value = values[i]
    -- process(value)
end
```
Reason: Numeric `for` avoids the iterator overhead of `pairs` and `ipairs` and directly indexes the sequential array.


```lua
-- Equivalent to: map(getSteamID, filter(isWantedAndAlive, player.GetAll()))
local function WantedAliveSteamIDs(players)
    local ids = {}
    local count = 0

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

        if IsValid(ply)
            and ply:Alive()
            and ply:getDarkRPVar("wanted") then
            count = count + 1
            ids[count] = ply:SteamID()
        end
    end

    return ids
end

local steamIDs = WantedAliveSteamIDs(player.GetAll())
```
Reason: One loop avoids callback dispatch and the intermediate table allocated by separate filter and map passes.


```lua
local cachedPlayers = {}

-- Populate once for players already connected when this file loads.
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
        -- Per-tick player logic here.
    end
end)
```
Reason: The player list is built once and updated only on join or leave, so Think iterates the cache without calling player.GetAll() every tick.


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

tempData[ply] = value
local value = tempData[ply]
```
Reason: A local table performs a direct lookup, avoiding the entity/metatable field-access path; weak keys allow entries to be collected when the player object is no longer referenced.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Dense sequential number-indexed arrays use faster array-style access than string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: Passing separate numeric channels avoids constructing or looking up a Color object in the hot draw path.


```lua
local result = sql.Query("SELECT value FROM player_data WHERE steamid = '...' LIMIT 1")
```
Reason: Local SQLite is typically lower latency because it avoids network round trips and remote MySQL connection overhead 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

-- Hot path:
local steamID = cachedSteamID(ply)
```
Reason: A weak-key cache avoids repeated SteamID() calls while allowing entries to be garbage-collected when player objects are released.


```lua
local pieces = {}

for i = 1, 10000 do
    pieces[i] = GetSmallPiece(i)
end

-- Slower: repeated concatenation
local slow = ""
for i = 1, #pieces do
    slow = slow .. pieces[i]
end

-- Faster: concatenate once
local fast = table.concat(pieces)
```
Reason: `table.concat` avoids repeatedly copying the growing string on every `..` operation.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the extra `draw.RoundedBox` helper overhead; set the color once when drawing many rectangles.


```lua
local font = "DermaDefault"
local text = "Single-line HUD text"

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` avoids the per-call wrapper work performed by `draw.DrawText` and `draw.SimpleTextOutlined`; use the direct surface state calls when no outline is needed.


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


```lua
t = {}
```
Reason: Replacing the table is generally faster because it avoids iterating over and niling every element; use `table.Empty(t)` only when existing references must observe the same table being emptied.


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

local weapon = "smg1"
if allowedWeapons[weapon] then
    print("Allowed")
end
```
Reason: Set lookup uses direct table-key access with average O(1) time, while `table.HasValue` scans the list in O(n) time.


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


```lua
local value = items[math.random(#items)]
```
Reason: Sequential tables use integer indices, so direct indexing avoids table.Random's key enumeration overhead.


```lua
local squared = x * x
```
Reason: Multiplication avoids the overhead of a function call and exponentiation logic.


```lua
for _, ply in player.Iterator() do
    -- Use ply here
end
```
Reason: player.Iterator() efficiently visits every currently connected player without creating an intermediate table.


```lua
for _, ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- Process ent here.
    end
end
```
Reason: ents.Iterator() streams entities one at a time without first creating a table of every entity.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` 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 the named incoming net message.


```lua
-- Fresh zeroed Angle in the hot path:
local a = angle_zero:Copy()

-- Slower equivalent:
-- local a = Angle()
```
Reason: `angle_zero:Copy()` creates a fresh Angle from the engine-provided zero value without invoking the constructor’s default initialization path.


```lua
local addonColor = Color(255, 255, 255)
local color = addonColor
```
Reason: A local flat variable avoids table traversal and global lookup, so it is fastest for frequent reads.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred over ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is DarkRP’s supported accessor for the player’s synchronized job name.


```lua
local threshold = 100

if firstVector:DistToSqr(secondVector) <= threshold * threshold then
    -- Vectors are within the threshold.
end
```
Reason: `DistToSqr` avoids the unnecessary square-root calculation; compare it with the threshold squared.


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


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

    return ents.FindInSphere(ply:GetPos(), radius)
end

local nearby = FindNearbyEntities(ply, 256)
for i = 1, #nearby do
    local ent = nearby[i]
    -- Handle ent here.
end
```
Reason: `ents.FindInSphere` is a native spatial-partition query with exact radial semantics, making it a practical fast choice for proximity checks without relying on PVS visibility.


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

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

    return nearbyPlayers
end
```
Reason: Iterate only the player list and compare squared distances, avoiding the broader entity spatial search and square-root calculations.


```lua
for i = 1, n do
    -- work
end
```
Reason: A numeric for loop is generally faster for counting in Garry's Mod Lua/LuaJIT because its loop control is optimized and avoids explicit increment and comparison operations.


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

hook.Add("CustomPlayerTick", "HandlePlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Custom logic for ply
    end
end)
```
Reason: One hook dispatch per tick avoids repeating hook.Run's lookup and dispatch overhead for every player.


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

    local health = ply:Health()

    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText("Status: " .. (health > 0 and "Alive" or "Dead"), "DermaDefault", 20, 40, color_white)
    draw.SimpleText("Value: " .. health, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache the player and health once per frame instead of calling `LocalPlayer():Health()` three times.


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

hook.Add("HUDPaint", "DrawSomething", function()
    surface.SetDrawColor(WHITE)
    surface.DrawRect(10, 10, 100, 100)
end)
```
Reason: Create the Color object once outside the paint loop and reuse it, avoiding per-frame allocation and garbage collection.


```lua
local sin = math.sin

for i = 1, iterations do
    local value = sin(i)
    -- use value
end
```
Reason: Local lookups are faster than repeatedly resolving the global `math` table and its `sin` field inside 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 ply = GetCachedLocalPlayer()
    if not IsValid(ply) then return end

    -- Use ply repeatedly instead of calling LocalPlayer() here.
    if ply:Alive() then
        -- hot-path logic
    end
end)
```
Reason: Cache the player entity in an upvalue and refresh it only when invalid, replacing repeated LocalPlayer() lookups with a cheaper local reference.


```lua
local LOOK_THRESHOLD = 0.8660254 -- cos(30 degrees)

local function ArePlayersLookingAtEachOther(playerA, playerB)
    local offset = playerB:EyePos() - playerA:EyePos()
    if offset:LengthSqr() == 0 then return false end

    local towardB = offset:GetNormalized()
    local towardA = -towardB

    return playerA:GetAimVector():Dot(towardB) >= LOOK_THRESHOLD
       and playerB:GetAimVector():Dot(towardA) >= LOOK_THRESHOLD
end
```
Reason: Dot products compare aim directions against the normalized direction between players without the cost of math.acos.


```lua
SomeHelper(ply)
```
Reason: It is generally faster when `SomeHelper` is a local/directly bound function because `ply:SomeHelper()` adds a member lookup and implicit receiver argument.


```lua
MsgN("[debug] hot-path event")
```
Reason: `MsgN` is Garry’s Mod’s native console-output function and avoids the extra overhead of Lua’s `print` wrapper.


```lua
local count = #values
local total = 0

for i = 1, count do
    total = total + values[i]
end
```
Reason: Numeric `for` with a cached length avoids iterator and key-traversal overhead, making it typically fastest for dense sequential arrays.


```lua
-- Equivalent to fn.Map(function(ply) return ply:Nick() end,
--     fn.Filter(function(ply) return IsValid(ply) and ply:Alive() end, player.GetAll()))

local players = player.GetAll()
local aliveNames = {}
local nameCount = 0

for i = 1, #players do
    local ply = players[i]
    if IsValid(ply) and ply:Alive() then
        nameCount = nameCount + 1
        aliveNames[nameCount] = ply:Nick()
    end
end
```
Reason: One fused numeric loop avoids intermediate tables, iterator overhead, and per-item filter/map closure calls.


```lua
local cachedPlayers = {}

-- Seed once when this file loads, including players already connected.
for _, ply in ipairs(player.GetAll()) do
    cachedPlayers[ply] = true
end

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

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

hook.Add("Think", "ProcessCachedPlayers", function()
    for ply in pairs(cachedPlayers) do
        if IsValid(ply) then
            -- Per-player work here.
        end
    end
end)
```
Reason: `player.GetAll()` runs only once and the cache changes on join or leave, so each tick iterates the existing player set without rebuilding a list.


```lua
local tempByPlayer = {}

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

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

hook.Add("PlayerDisconnected", "ClearTempByPlayer", function(ply)
    tempByPlayer[ply] = nil
end)
```
Reason: A local side table uses a direct table lookup and avoids the entity userdata field lookup/metamethod path; explicit disconnect cleanup prevents stale player references.


```lua
-- Prefer a sequential number-indexed array for fixed collections.
local values = { "alpha", "beta", "gamma" }

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential numeric arrays use Lua's array storage and direct integer indexing, avoiding hash lookups required by string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: Passing channel numbers avoids per-call 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 avoids network round trips and connection overhead, 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 SteamID is resolved once per player and reused, avoiding repeated engine calls while disconnect cleanup prevents stale entries.


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

-- Faster: collect pieces, then join them once.
local parts = {}
for i = 1, #pieces do
    parts[i] = pieces[i]
end
local fast = table.concat(parts)
```
Reason: table.concat avoids repeatedly copying the growing string, reducing large concatenations from quadratic behavior toward linear behavior.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, avoiding the extra zero-radius `draw.RoundedBox` wrapper overhead.


```lua
local text = "Single-line HUD text"
local font = "Trebuchet24"

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(32, 32)
    surface.DrawText(text)
end)
```
Reason: Direct surface calls avoid the extra wrapper and repeated outline draws used by draw.DrawText and draw.SimpleTextOutlined.


```lua
local length = #myTable
```
Reason: For a sequential array-like table, Lua’s `#` length operator is the idiomatic choice; `table.Count` counts all keys.


```lua
t = {}
```
Reason: `t = {}` replaces the table in constant time, while `table.Empty(t)` traverses and clears every entry; use `table.Empty` only when existing references must remain valid.


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

if allowed[value] then
    -- value exists in the set
end
```
Reason: Set-style tables use near-constant-time key lookup, while table.HasValue scans the list linearly.


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


```lua
local items = { "a", "b", "c" }
local randomItem = items[math.random(#items)]
```
Reason: Direct indexing avoids the extra general-table handling used by `table.Random`.


```lua
local squared = x * x
```
Reason: Multiplication avoids exponentiation overhead and is the fastest clear form for squaring.


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Visit ent here.
    end
end
```
Reason: ents.Iterator() streams entities without allocating the full map entity table that ents.GetAll() would build.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` returns false for nil, NULL, removed, or otherwise invalid entity references before you call entity methods.


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


```lua
local ZERO_ANGLE = angle_zero -- built-in Angle(0, 0, 0); never mutate this

local function freshZeroAngle()
    return ZERO_ANGLE * 1 -- fresh Angle, faster than Angle(0, 0, 0) / Angle()
end
```
Reason: Copying the engine-provided zero angle through the Angle metatable is cheaper than repeatedly going through the Lua Angle constructor in a hot path.


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

surface.SetDrawColor(addonColor)
```
Reason: A local variable is fastest for frequent reads because it avoids global lookup and nested table indexing.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: DarkRP stores a player's job as their team, so `team.GetName(ply:Team())` reads the authoritative local team data and avoids slower networked-string lookup via `ply:GetNWString("job")`.


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


```lua
for ent in ents.Iterator() do
    -- Use ent here.
end
```
Reason: `ents.Iterator()` visits every entity without building the full `ents.GetAll()` table first, which is the wiki-recommended efficient path for simple full-entity iteration.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if ent ~= ply and IsValid(ent) then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a cheap built-in spatial query for radius checks around a player and is commonly faster than broad Lua-side filtering.


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

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

    return nearby
end
```
Reason: Iterating `player.GetAll()` checks only players and uses squared distance, avoiding the broader entity sphere query and the square root cost.


```lua
local i = 1
while i <= n do
    -- work
    i = i + 1
end
```
Reason: In Garry's Mod Lua, a tight numeric `while` loop is generally faster than a numeric `for` loop because it avoids the extra generic loop control overhead in this runtime.


```lua
hook.Run("MyTickForPlayers", player.GetAll())

hook.Add("MyTickForPlayers", "MyAddon.ProcessPlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom logic for ply
    end
end)
```
Reason: `hook.Run` does dispatch and lookup work each call, so doing it once per tick and looping players inside the listener avoids repeated hook overhead.


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

    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 20, color_white)
    draw.RoundedBox(4, 20, 45, math.Clamp(health, 0, 100) * 2, 16, Color(220, 60, 60))
    draw.SimpleText(health .. "%", "DermaDefault", 230, 43, color_white)
end)
```
Reason: Cache `LocalPlayer():Health()` once per HUDPaint frame so the three draw calls reuse the same value instead of doing repeated method lookups/calls.


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

hook.Add("HUDPaint", "DrawThings", function()
    for _, item in ipairs(items) do
        surface.SetDrawColor(white)
        -- draw item here
    end
end)
```
Reason: `Color(...)` allocates a table, so create the constant once outside the hot paint loop and reuse it.


```lua
local sin = math.sin

for i = 1, count do
    total = total + sin(i)
end
```
Reason: Caching `math.sin` in a local avoids repeated global/table lookups inside the hot loop; local variable access is faster in Lua.


```lua
local ply

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

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

    if IsValid(ply) then
        -- Use ply here instead of calling LocalPlayer() repeatedly.
        local pos = ply:GetPos()
    end
end)
```
Reason: Cache the local player once after it exists, then refresh only if it becomes invalid, avoiding repeated global LocalPlayer() lookups in hot client code.


```lua
local function AreRoughlyLookingAtEachOther(plyA, plyB, minDot)
    minDot = minDot or 0.7 -- higher = stricter, 0.7 is roughly within 45 degrees

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

    return plyA:GetAimVector():Dot(aToB) >= minDot
        and plyB:GetAimVector():Dot(bToA) >= minDot
end
```
Reason: Dot products avoid `math.acos`; comparing against a cosine threshold is cheaper and enough for a rough facing check.


```lua
SomeHelper(ply)
```
Reason: Faster generally, because a local/plain helper call avoids the per-call method lookup and implicit self dispatch of `ply:SomeHelper()`.


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


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: A numeric for loop is typically fastest for large sequential array-like tables because it avoids the iterator overhead of pairs/ipairs and does direct integer index access.


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

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

    if IsValid(ply) and ply:Alive() and ply:Team() == TEAM_CITIZEN then
        n = n + 1
        out[n] = {
            ply = ply,
            name = ply:Nick(),
            money = ply:getDarkRPVar("money") or 0,
        }
    end
end

return out
```
Reason: One tight indexed loop avoids fn's chained closures, iterator dispatch, and intermediate filter/map tables while doing the same transform.


```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("Tick", "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 the player list, so doing it only on join/leave removes that repeated per-tick work while numeric iteration avoids `ipairs` overhead.


```lua
local tempByPlayer = {}

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

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

local function GetTemp(ply)
    return tempByPlayer[ply]
end
```
Reason: Reading from a local table avoids repeated entity metatable/index lookup overhead from `ply.someField`, so hot-path per-player reads are cheaper.


```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 Lua can walk dense integer slots with simple numeric indexing instead of hash lookups.


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

hook.Add("HUDPaint", "HotDrawPath", function()
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(32, 32, 160, 24)
end)
```
Reason: Passing separate numeric channels avoids the Color table/object path and is faster in a hot draw loop.


```lua
local steamId = sql.SQLStr(ply:SteamID64())
local row = sql.QueryRow("SELECT coins FROM player_data WHERE steam_id = " .. steamId .. " LIMIT 1")
```
Reason: Local SQLite is typically lower latency because it avoids network round trips to a remote MySQL server for a single-server, no-sync workload.


```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", "ClearSteamIDCache", function(ply)
    steamIdCache[ply] = nil
end)
```
Reason: Caches the expensive method result per Player object, uses weak keys so stale players can be collected, and clears explicitly on disconnect.


```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 `..` concatenation keeps copying the growing string over and over.


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


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetTextPos` + `surface.DrawText` is the lower-level path for a single line and avoids the extra alignment, newline, outline, and helper work in `draw.DrawText` / `draw.SimpleTextOutlined`.


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


```lua
t = {}
```
Reason: Rebinding drops the old large table in O(1) and lets GC reclaim it later; table.Empty(t) must walk and clear every entry, so use it only when other references must see the same table emptied.


```lua
local allowed = {
    weapon_pistol = true,
    weapon_smg1 = true,
    weapon_crowbar = true,
}

if allowed[className] then
    -- value exists in the set
end
```
Reason: Direct table key lookup is O(1) average-case, while table.HasValue scans the list O(n) each check.


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


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


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


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent
    end
end
```
Reason: ents.Iterator() streams entities without allocating the full ents.GetAll()/ents.FindByClass() result table, and the class check keeps only prop_physics.


```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(ent)` checks that the entity reference is non-nil, not NULL, and still valid before you call entity methods on it.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Read and handle the incoming message here.
end)
```
Reason: `net.Receive` registers a callback for the named net message and runs it when `MyAddon.Sync` is received.


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

-- Fast when the Angle is only scratch state for this path.
local scratchAng = Angle(0, 0, 0)

local function fast()
    scratchAng:Zero()
    return scratchAng
end
```
Reason: Reusing one scratch Angle and zeroing it avoids repeated Angle userdata allocation; only use this when callers will not store or mutate the returned reference beyond the hot-path operation.


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

local color = configColor
```
Reason: A flat local is fastest because it avoids global lookup and repeated nested table indexing on every read.


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

-- Instead of:
-- local jobName = ply:GetNWString("job")
```
Reason: DarkRP owns and synchronizes player job state through DarkRPVars, so `getDarkRPVar("job")` uses the framework API instead of relying on raw NWString storage details.


```lua
local maxDistance = 500

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


```lua
for ent in ents.Iterator() do
    -- Visit ent here.
end
```
Reason: `ents.Iterator()` visits all entities without building the `ents.GetAll()` table first, which is the wiki-recommended efficient path when you only need to iterate.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if ent ~= ply and IsValid(ent) then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a cheap built-in spatial query for entities near a point and is commonly faster than broader visibility-style searches for this job.


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

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

    return found
end
```
Reason: Iterating `player.GetAll()` checks only players and uses squared distance, avoiding the broader entity sphere query, class filtering, and square-root cost.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric for loops are generally faster for tight 1-to-n counting because Lua handles the counter, limit, and increment in the loop opcode instead of doing explicit while-condition checks and increments in Lua.


```lua
hook.Add("Tick", "NotifyCustomLogic", function()
    local players = player.GetAll()

    -- Faster: one hook dispatch per tick; listeners loop only if they need to.
    hook.Run("CustomLogicForPlayers", players)

    -- Slower: one hook dispatch per player per tick.
    -- for _, ply in ipairs(players) do
    --     hook.Run("CustomLogicForPlayer", ply)
    -- end
end)
```
Reason: `hook.Run` has dispatch overhead, so paying it once per tick and passing the player list is faster than paying it once per player.


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

    draw.SimpleText("HP: " .. health, "DermaDefault", 20, 20, color_white)
    draw.RoundedBox(4, 20, 45, math.max(health, 0) * 2, 16, Color(220, 60, 60))
    draw.SimpleText(health .. "%", "DermaDefault", 20, 68, color_white)
end)
```
Reason: Cache `LocalPlayer()` and `Health()` once per frame so the three draw calls reuse local values instead of repeating method lookups/calls.


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

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

    for i = 1, 100 do
        -- draw work here
    end
end)
```
Reason: Allocate the Color object once outside the paint loop and reuse it, avoiding per-frame/per-iteration table creation and GC pressure.


```lua
local sin = math.sin

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


```lua
local cachedLocalPlayer

local function LP()
    if IsValid(cachedLocalPlayer) then
        return cachedLocalPlayer
    end

    cachedLocalPlayer = LocalPlayer()
    return cachedLocalPlayer
end

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

-- Hot path example:
hook.Add("Think", "UseCachedLocalPlayer", function()
    local ply = LP()
    if not IsValid(ply) then return end

    -- use ply here instead of calling LocalPlayer() repeatedly
end)
```
Reason: Cache the LocalPlayer entity after it exists, then reuse the local reference on hot paths while revalidating it so you avoid repeated global LocalPlayer() lookups.


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

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

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

    aToB:Normalize()
    local bToA = -aToB

    return a:GetAimVector():Dot(aToB) >= LOOK_DOT
       and b:GetAimVector():Dot(bToA) >= LOOK_DOT
end
```
Reason: Dot products compare facing direction against a cosine threshold directly, avoiding `math.acos` and angle construction.


```lua
SomeHelper(ply)
```
Reason: Faster generally, because it avoids the `ply` method/metatable lookup that `ply:SomeHelper()` needs before passing `ply` as `self`.


```lua
MsgN("debug: hot path reached")
```
Reason: `MsgN` writes directly to the console with a newline and avoids the extra formatting overhead of `print`.


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


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

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

    if IsValid(ply) and ply:Alive() and ply:getDarkRPVar("job") == TEAM_POLICE then
        n = n + 1
        out[n] = {
            ent = ply,
            name = ply:Nick(),
            salary = ply:getDarkRPVar("salary") or 0,
        }
    end
end
```
Reason: One fused numeric loop avoids fn's per-step closures, iterator dispatch, and intermediate tables while doing the same filter/map work.


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

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

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

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

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

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

    if lastPlayer ~= ply then
        playerIndex[lastPlayer] = index
    end
end

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

hook.Add("PlayerInitialSpawn", "CacheJoinedPlayer", AddCachedPlayer)
hook.Add("PlayerDisconnected", "CacheLeftPlayer", RemoveCachedPlayer)

hook.Add("Tick", "FastPlayerTick", 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()` and `ipairs` are no longer run every tick; the hot path iterates one maintained array, while join/leave hooks pay the update cost only when membership changes.


```lua
local playerTemp = {}

hook.Add("PlayerInitialSpawn", "InitTempData", function(ply)
    playerTemp[ply] = { score = 0 }
end)

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

local function SetTempScore(ply, value)
    playerTemp[ply].score = value
end

local function GetTempScore(ply)
    return playerTemp[ply].score
end
```
Reason: A local Lua table keyed by `ply` avoids repeated entity/userdata field lookup overhead and keeps hot reads on plain table access.


```lua
-- Faster for fixed iteration: sequential number-indexed array
local values = { "health", "armor", "ammo" }

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays iterate faster than string-keyed maps because Lua can walk contiguous integer slots with a numeric for loop instead of hashing keys via pairs().


```lua
-- Hot draw path: pass raw channels, not a Color object.
surface.SetDrawColor(255, 80, 40, 255)
```
Reason: Separate r, g, b, a numbers avoid Color object table lookup/allocation overhead in repeated draw calls.


```lua
local steamId = sql.SQLStr(ply:SteamID64())
local rows = sql.Query("SELECT money, rank FROM player_data WHERE steam_id = " .. steamId .. " LIMIT 1")
```
Reason: Local SQLite via Garry's Mod's `sql` library is typically lower latency for a single server because reads/writes avoid remote network round trips and multi-server coordination is not needed.


```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", "ClearCachedSteamID", function(ply)
    steamIDCache[ply] = nil
end)

-- Hot path:
for _, ply in ipairs(player.GetAll()) do
    local steamID = CachedSteamID(ply)
    -- use steamID here
end
```
Reason: Cache by Player entity with weak keys so each player's SteamID is computed once, reused on the hot path, and cleared when the player leaves.


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

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

local result = table.concat(parts)
```
Reason: table.concat builds the final string in one join step, avoiding repeated copying of an ever-growing string.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws the rectangle directly and avoids the extra `draw.RoundedBox` wrapper work when the radius is `0`.


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

local setFont = surface.SetFont
local setTextColor = surface.SetTextColor
local setTextPos = surface.SetTextPos
local drawText = surface.DrawText

hook.Add("HUDPaint", "FastSingleLineText", function()
    setFont(font)
    setTextColor(color)
    setTextPos(x, y)
    drawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextColor` + `surface.SetTextPos` + `surface.DrawText` avoids the extra wrapper work in `draw.DrawText` and the much heavier repeated draws used by `draw.SimpleTextOutlined`.


```lua
local count = #items
```
Reason: `#` is the preferred length operator for sequential array-like tables; avoid `table.Count` unless you need to count non-sequential/hash keys.


```lua
t = {}
```
Reason: Replacing the table is generally faster because it avoids clearing every existing entry one by one; use table.Empty(t) only when other references must keep the same table object.


```lua
local allowed = {
    weapon_physgun = true,
    weapon_crowbar = true,
    weapon_pistol = true,
}

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


```lua
local t = {
    name = "prop_physics",
    count = 3,
    enabled = true,
}
```
Reason: Putting known fields in the table constructor is faster because Lua creates and fills the table in one step instead of creating an empty table and then doing separate field assignments.


```lua
local value = items[math.random(#items)]
```
Reason: For a sequential table, direct numeric indexing avoids `table.Random` walking the table and is O(1).


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


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent
    end
end
```
Reason: `ents.Iterator()` walks entities lazily, so it avoids allocating a full entity table before filtering by class.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` rejects nil/NULL/removed entities, so method calls only run on a usable entity reference.


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


```lua
local zero = angle_zero

-- Hot path: creates a new mutable Angle copied from the cached zero Angle.
local function FreshZeroAngle()
    return zero * 1
end

-- Slower in tight loops:
-- local ang = Angle()
```
Reason: `angle_zero * 1` copies the engine-provided zero Angle and avoids the slower Lua constructor path for `Angle()`.


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

local color = configColor
```
Reason: A flat local variable is fastest because it avoids repeated global and nested table lookups.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred
-- local jobName = ply:GetNWString("job") -- avoid for DarkRP jobs
```
Reason: DarkRP owns and syncs job data through DarkRPVars, so `getDarkRPVar("job")` uses the framework contract instead of reading a raw networked string directly.


```lua
local maxDistance = 250

if pos1:DistToSqr(pos2) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root used for actual distance, 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
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- visit ent
    end
end
```
Reason: `ents.Iterator()` avoids building the full `ents.GetAll()` table on newer Garry's Mod versions, while the fallback keeps older versions working.


```lua
local radius = 512
local radiusSqr = radius * radius

local function FindEntitiesNearPlayer(ply)
    local origin = ply:GetPos()
    local mins = origin - Vector(radius, radius, radius)
    local maxs = origin + Vector(radius, radius, radius)
    local nearby = {}

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

    return nearby
end
```
Reason: `ents.FindInBox` is a fast built-in broadphase query in common GMod benchmarks, and the squared-distance filter keeps the result circular without paying `FindInSphere` cost.


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

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

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


```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 repeated explicit condition/increment work.


```lua
-- Slower: dispatches the hook once per player every tick.
hook.Add("Tick", "NotifyPlayersSlow", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("MyPerPlayerTick", ply)
    end
end)

-- Faster: one hook dispatch per tick; receivers loop the player list if needed.
hook.Add("Tick", "NotifyPlayersFast", function()
    hook.Run("MyPlayersTick", player.GetAll())
end)

hook.Add("MyPlayersTick", "CustomLogic", function(players)
    for _, ply in ipairs(players) do
        -- custom per-player logic here
    end
end)
```
Reason: `hook.Run` has dispatch overhead, so doing it once per tick and passing all players is cheaper than doing one hook dispatch per player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText("HP: " .. health, "DermaDefault", 20, 40, color_white)
    draw.RoundedBox(4, 20, 60, health * 2, 12, Color(220, 60, 60))
end)
```
Reason: LocalPlayer() and Health() are resolved once per HUDPaint frame instead of repeating the same Lua/C++ calls three times.


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

hook.Add("HUDPaint", "FastPaintLoop", function()
    for i = 1, 100 do
        draw.SimpleText("Label", "DermaDefault", 16, i * 14, COLOR_WHITE)
    end
end)
```
Reason: Build the Color table once and reuse it, avoiding per-frame per-iteration allocations in the paint hot path.


```lua
local sin = math.sin

for i = 1, count do
    values[i] = sin(i * step)
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 only refresh it when it becomes invalid, avoiding repeated global LocalPlayer() lookups in hot code.


```lua
local LOOK_COS = math.cos(math.rad(25)) -- smaller angle = stricter check

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

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

    aToB:Normalize()

    return a:GetAimVector():Dot(aToB) >= LOOK_COS
       and b:GetAimVector():Dot(-aToB) >= LOOK_COS
end
```
Reason: Dot products compare normalized directions against a precomputed cosine threshold, avoiding expensive `math.acos` angle calculations.


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

SomeHelper(ply)
```
Reason: Faster in general for controlled helpers because a local function call avoids the per-call method/table lookup behind `ply:SomeHelper()`; use colon when the helper belongs on the object API.


```lua
local writeConsole = Msg

writeConsole("[debug] hot path reached\n")
```
Reason: `Msg` is a lower-level console write than `print`, avoiding `print`'s extra argument formatting and newline handling.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: Numeric `for` is typically fastest for a large sequential array-like table because it avoids iterator function overhead from `pairs`/`ipairs` and does direct integer indexing.


```lua
local IsValid = IsValid
local teamGetName = team.GetName

local function wantedRichPlayers(players, minMoney)
    local out = {}
    local outN = 0

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

        if IsValid(ply) and not ply:isArrested() and ply:getDarkRPVar("wanted") then
            local money = ply:getDarkRPVar("money") or 0

            if money >= minMoney then
                outN = outN + 1
                out[outN] = {
                    ply = ply,
                    name = ply:Nick(),
                    job = teamGetName(ply:Team()),
                    money = money
                }
            end
        end
    end

    return out
end

local rows = wantedRichPlayers(player.GetAll(), 10000)
```
Reason: This fuses filter and map into one numeric loop, avoiding DarkRP fn closures, chained iterator calls, and intermediate tables.


```lua
local cachedPlayers = {}
local cachedPlayerCount = 0

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

hook.Add("Initialize", "MyAddon_PlayerCache_Init", RefreshPlayerCache)

hook.Add("PlayerInitialSpawn", "MyAddon_PlayerCache_Join", function()
    RefreshPlayerCache()
end)

hook.Add("PlayerDisconnected", "MyAddon_PlayerCache_Leave", function()
    timer.Simple(0, RefreshPlayerCache) -- wait until the leaving player is gone from player.GetAll()
end)

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

        -- per-player tick work here
    end
end)
```
Reason: `player.GetAll()` allocates/builds the player list only on join/leave, while the hot Think path reuses the cached array with a numeric loop.


```lua
local staminaByPlayer = {}

local function SetStamina(ply, stamina)
    staminaByPlayer[ply] = stamina
end

local function GetStamina(ply)
    return staminaByPlayer[ply]
end

hook.Add("PlayerDisconnected", "ClearTempStamina", function(ply)
    staminaByPlayer[ply] = nil
end)
```
Reason: A plain Lua side table keyed by player avoids repeated entity field lookup overhead and keeps cleanup explicit for temporary data.


```lua
local values = {
    "health",
    "armor",
    "ammo",
    "position",
}

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


```lua
surface.SetDrawColor(255, 80, 40, 255)
```
Reason: Passing numeric channels avoids the Color object/table path and is faster in a hot draw loop.


```lua
local steamID64 = ply:SteamID64()
local row = sql.QueryRow("SELECT money, rank FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64) .. " LIMIT 1")
```
Reason: local SQLite avoids remote network round trips, so it is typically lower latency for a single Garry's Mod server with no multi-server sync need.


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

local function FastSteamID(ply)
    local id = steamIdCache[ply]
    if id ~= nil then return id end

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

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

-- hot path
local id = FastSteamID(ply)
```
Reason: `ply:SteamID()` crosses the Lua/C++ method boundary each call; caching once per player entity turns repeated hot-path lookups into a table read while clearing stale entries on disconnect.


```lua
-- Slower: reallocates/copies the growing string each iteration.
local result = ""
for i = 1, 10000 do
    result = result .. tostring(i) .. ","
end

-- Faster: collect pieces, then concatenate once.
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = tostring(i)
    pieces[#pieces + 1] = ","
end

local fastResult = table.concat(pieces)
```
Reason: `table.concat` avoids repeatedly copying the entire growing string, so it scales much better for thousands of pieces.


```lua
surface.SetDrawColor(col)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the `draw.RoundedBox` wrapper work; hoist `surface.SetDrawColor` when drawing many rectangles with the same color.


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

surface.SetFont(font)
local textW, textH = surface.GetTextSize(text) -- cache if text/font do not change

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(color)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetTextPos` + `surface.DrawText` avoids the extra wrapping/alignment/outline work in `draw.DrawText` and `draw.SimpleTextOutlined`, and caching `GetTextSize` avoids per-frame measurement when the string is stable.


```lua
local count = #items
```
Reason: `#` is the native length operator for sequential array-like tables; `table.Count` is for counting all keys in a table.


```lua
t = {}
```
Reason: Rebinding to a fresh table is generally faster for large tables because it avoids walking and niling every existing entry; use table.Empty(t) only when other references must keep seeing the same table.


```lua
-- Slower: scans the list every time
local roles = { "admin", "moderator", "vip" }
if table.HasValue(roles, plyRole) then
    -- allowed
end

-- Faster: set-style table with O(1) lookup
local roleSet = {
    admin = true,
    moderator = true,
    vip = true,
}

if roleSet[plyRole] then
    -- allowed
end
```
Reason: `table.HasValue` linearly scans the list, while keyed lookup checks the set directly.


```lua
local t = {
    x = 10,
    y = 20,
    name = "crate",
}
```
Reason: The table constructor is faster because Lua creates and initializes the known fields in one operation instead of creating an empty table and then running separate field assignments.


```lua
local random = math.random

local function FastRandomSequential(t)
    return t[random(#t)]
end
```
Reason: For a sequential table, indexing with `math.random(#t)` avoids `table.Random`'s generic table traversal work.