```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Visit ent here.
    end
end
```
Reason: `ents.Iterator()` traverses entities directly, so the loop filters `prop_physics` entities without allocating the table returned by `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers a uniquely identified callback that runs whenever the Think hook fires.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid checks that ent exists and has not been removed before you call entity methods.


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


```lua
local zeroAngle = angle_zero

-- Hot path
local ang = zeroAngle
```
Reason: Reusing Garry's Mod's shared zero Angle avoids the allocation and constructor cost of calling Angle() each time.


```lua
local color = Color(255, 255, 255)
local currentColor = color
```
Reason: A local variable is fastest because Lua resolves it directly, while nested tables require multiple hash lookups per read.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP exposes the job through its replicated DarkRP variable API; use `getDarkRPVar("job")` instead of reading the underlying networked string directly.


```lua
if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- Within range
end
```
Reason: `Vector:DistToSqr` avoids the square root required for actual distance while preserving threshold comparisons.


```lua
for ent in ents.Iterator() do
    -- Use ent
end
```
Reason: `ents.Iterator()` visits every entity without first allocating the table returned by `ents.GetAll()`, making it the preferred efficient iterator when the loop only needs traversal.


```lua
local nearbyEntities = ents.FindInSphere(ply:GetPos(), 512)
```
Reason: ents.FindInSphere is a fast built-in spatial query for a simple radius search and avoids scanning every entity in Lua.


```lua
local function FindPlayersNear(position, radius)
    local nearby = {}
    local radiusSquared = radius * radius
    local players = player.GetAll()

    for i = 1, #players do
        local ply = players[i]
        if ply:GetPos():DistToSqr(position) <= radiusSquared then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```
Reason: Iterating only `player.GetAll()` avoids scanning every entity, and squared-distance checks avoid a square root per player.


```lua
local i = 1
while i <= n do
    -- work
    i = i + 1
end
```
Reason: In Garry's Mod Lua, a simple numeric while loop is generally faster than a numeric for loop.


```lua
hook.Add("Tick", "NotifyCustomLogic", function()
    hook.Run("CustomLogicTick", player.GetAll())
end)
```
Reason: One hook.Run call per tick avoids repeated hook dispatch overhead; listeners can loop over the supplied players themselves.


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

draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
draw.SimpleText(health, "DermaDefault", 20, 40, color_white)
draw.SimpleText(health, "DermaDefault", 20, 60, color_white)
```
Reason: Cache the health value once per HUDPaint call to avoid two redundant LocalPlayer and Health method calls in the same frame.


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

for _, item in ipairs(items) do
    surface.SetDrawColor(white)
    -- draw item
end
```
Reason: Creating the color once outside the loop avoids repeated table allocation and initialization on every iteration.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

-- Hot path
hook.Add("Think", "UseCachedLocalPlayer", function()
    if IsValid(localPlayer) then
        -- Use localPlayer here instead of calling LocalPlayer() repeatedly.
    end
end)
```
Reason: Caching the player in a local upvalue avoids repeated global function lookup and LocalPlayer() calls on hot paths.


```lua
local function ArePlayersLookingAtEachOther(a, b, minDot)
    minDot = minDot or 0.8

    local direction = (b:EyePos() - a:EyePos()):GetNormalized()
    return a:GetAimVector():Dot(direction) >= minDot
       and b:GetAimVector():Dot(-direction) >= minDot
end
```
Reason: Dot-product threshold checks avoid the expensive `math.acos`; normalizing one displacement and negating it supplies both player-to-player directions.


```lua
SomeHelper(ply)
```
Reason: A direct function call generally avoids the metatable method lookup that `ply:SomeHelper()` requires; the colon itself only adds `ply` as the first argument.


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


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: A numeric for loop typically has the least iterator overhead for a large dense sequential table, making it faster than ipairs and pairs.


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

for i = 1, #players do
    local ply = players[i]
    if ply:isArrested() then
        count = count + 1
        result[count] = ply:Nick()
    end
end
```
Reason: A fused numeric loop avoids combinator callbacks and intermediate filter tables, reducing function-call and allocation overhead.


```lua
local cachedPlayers = {}

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

hook.Add("InitPostEntity", "RefreshPlayerCache", refreshPlayerCache)
hook.Add("PlayerInitialSpawn", "RefreshPlayerCache", refreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCache", function()
    timer.Simple(0, refreshPlayerCache)
end)

hook.Add("Tick", "ProcessCachedPlayers", 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 cache allocation happen only when membership changes, while each tick uses a fast numeric loop over the cached table.


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

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

local function GetPlayerValue(ply)
    return playerData[ply]
end
```
Reason: A local table indexed by the player avoids slower userdata/metatable field reads, while weak keys let removed players be garbage-collected.


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

for index = 1, #values do
    local value = values[index]
end
```
Reason: Sequential number-indexed arrays use the faster array storage and numeric iteration path, avoiding string-key hashing and `pairs` overhead.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numeric channels avoids creating or unpacking a Color object in the hot draw path.


```lua
sql.Query("SELECT * FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64))
```
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 steamID == nil then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: A weak-key cache computes each valid player's stable SteamID once without keeping disconnected player objects alive.


Answer must contain 0 through 0 candidate loops.

```lua
local pieces = {}

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

local result = table.concat(pieces)
```
Reason: Collecting pieces and joining once with table.concat avoids repeatedly allocating and copying an ever-growing string.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, avoiding the extra work and dispatch in `draw.RoundedBox(0, ...)`.


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

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetTextPos(20, 20)
    surface.DrawText("Fast single-line text")
end)
```
Reason: surface.SetTextPos plus surface.DrawText is the lowest-overhead path for plain single-line text; draw.DrawText adds multiline handling, while SimpleTextOutlined performs extra draws for the outline.


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


```lua
t = {}
```
Reason: Rebinding to a new empty table is generally faster because it avoids iterating over and clearing every entry in the old table; use table.Empty(t) only when other references must see the same table emptied.


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

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


```lua
local playerData = {
    health = 100,
    armor = 50,
    alive = true,
}
```
Reason: Putting known fields directly in the table constructor avoids separate post-creation assignment operations and is faster.


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


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the overhead of exponentiation for a fixed square.


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

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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process ent here.
    end
end
```
Reason: `ents.Iterator()` visits entities directly, avoiding the full table allocation performed by `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers a uniquely identified callback that runs on every Think hook.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid confirms the reference exists and is not a removed entity before methods are called.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Read and handle the incoming message here.
end)
```
Reason: `net.Receive` registers a callback for incoming messages with the specified network-string name.


```lua
local zeroedAngle = angle_zero * 1
```
Reason: Multiplying the cached zero Angle creates a fresh zeroed Angle faster than calling Angle() in the hot path.


```lua
local configColor = Color(255, 255, 255)
local color = configColor
```
Reason: A local variable is fastest to read because it avoids global and nested table lookups.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP owns and synchronizes the job value through its DarkRPVar API, so use `getDarkRPVar("job")` instead of reading the underlying networked string directly.


```lua
if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- Within range
end
```
Reason: `Vector:DistToSqr` avoids the square-root calculation required for the actual distance.


```lua
for ent in ents.Iterator() do
    -- Process ent
end
```
Reason: `ents.Iterator()` visits every entity without first allocating the table returned by `ents.GetAll()`, making it the preferred efficient iterator when only traversal is needed.


```lua
local nearbyEntities = ents.FindInSphere(player:GetPos(), 512)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for a radius around the player and avoids the broader visibility semantics of `FindInPVS`.


```lua
local function FindPlayersInRadius(position, radius)
    local nearby = {}
    local radiusSquared = radius * radius
    local players = player.GetAll()

    for i = 1, #players do
        local ply = players[i]
        if position:DistToSqr(ply:GetPos()) <= radiusSquared then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```
Reason: Iterating the player list avoids scanning every entity, and squared distance avoids a square-root calculation per player.


```lua
local i = 1
while i <= n do
    -- work
    i = i + 1
end
```
Reason: In Garry's Mod Lua (LuaJIT), a simple `while` loop is generally faster than a numeric `for` loop.


```lua
hook.Add("Tick", "NotifyCustomLogic", function()
    hook.Run("CustomLogicForPlayers", player.GetAll())
end)

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


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

    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(health .. " HP", "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health <= 25 and "LOW HEALTH" or "", "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache Health() once per HUDPaint call so all three draw calls reuse the same value and avoid two method calls.


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

for i = 1, itemCount do
    drawItem(i, white)
end
```
Reason: Reusing one Color object avoids allocating a new color table on every paint-loop iteration.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

hook.Add("Think", "FastClientLogic", function()
    if not IsValid(localPlayer) then return end

    -- Use localPlayer here instead of calling LocalPlayer() repeatedly.
end)
```
Reason: Cache the player once after client entities initialize, so hot code reads a fast Lua local instead of repeating the engine lookup.


```lua
local function AreRoughlyLookingAtEachOther(ply1, ply2)
    local towardPly2 = (ply2:EyePos() - ply1:EyePos()):GetNormalized()
    local threshold = 0.8 -- roughly within 37 degrees

    return ply1:GetAimVector():Dot(towardPly2) >= threshold
       and ply2:GetAimVector():Dot(towardPly2) <= -threshold
end
```
Reason: Dot products compare alignment directly, avoiding the relatively expensive math.acos angle conversion.


```lua
SomeHelper(ply)
```
Reason: A direct function call generally avoids the metatable lookup required by ply:SomeHelper(), so it is usually faster for a helper you control.


```lua
Msg("debug line\n")
```
Reason: Msg writes the string directly, avoiding print's argument formatting and tab-separation overhead.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: A numeric for loop typically has the least iterator overhead for a dense sequential array, making it faster than ipairs and pairs.


```lua
local names = {}
local count = 0

for i = 1, #players do
    local ply = players[i]
    if IsValid(ply) and ply:Alive() then
        count = count + 1
        names[count] = ply:Nick()
    end
end
```
Reason: One fused numeric loop avoids fn combinator callbacks and intermediate tables while performing the same filter-then-map work.


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

for index, ply in ipairs(cachedPlayers) do
    playerIndex[ply] = index
end

hook.Add("PlayerInitialSpawn", "CachedPlayers.Add", function(ply)
    if playerIndex[ply] then return end

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

hook.Add("PlayerDisconnected", "CachedPlayers.Remove", function(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 index ~= lastIndex then
        playerIndex[lastPlayer] = index
    end
end)

hook.Add("Tick", "ProcessCachedPlayers", function()
    for index = 1, #cachedPlayers do
        local ply = cachedPlayers[index]
        -- Per-player tick work here.
    end
end)
```
Reason: The hot path reuses one dense array, while join is O(1) append and leave is O(1) swap-remove, avoiding player.GetAll() and its table allocation every tick.


```lua
local playerData = {}

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

-- Write
playerData[ply] = value

-- Hot read
local value = playerData[ply]
```
Reason: A module-local table indexed by the player avoids repeated userdata/metatable field lookup, making hot reads faster while explicit disconnect cleanup prevents stale entries.


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

for i = 1, #values do
    local value = values[i]
end
```
Reason: Sequential number-indexed arrays are faster to iterate because numeric indexing avoids hash-key lookup and a numeric for loop avoids iterator overhead.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Separate numeric arguments avoid the Color object overload and its table access/type-handling overhead in the hot draw path.


```lua
local row = sql.QueryRow("SELECT credits FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64))
```
Reason: Local SQLite typically has lower read/write latency because it avoids network round trips to a remote MySQL server.


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

local function getSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID == nil then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: A weak-key cache pays for `SteamID()` once per player entity, makes later hot-path reads plain table lookups, and releases entries after disconnected player entities are collected.


```lua
local pieces = {}

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

local result = table.concat(pieces)
```
Reason: Collecting pieces in a table and joining once with table.concat avoids repeatedly allocating and copying an ever-growing intermediate string.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: `surface.DrawRect` directly draws a non-rounded rectangle, avoiding the extra overhead of `draw.RoundedBox(0, ...)`.


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

hook.Add("HUDPaint", "FastSingleLineText", function()
    setFont("DermaDefault")
    setTextColor(255, 255, 255, 255)
    setTextPos(24, 24)
    drawText("Single-line text")
end)
```
Reason: Direct surface.DrawText avoids draw.DrawText's multiline processing and SimpleTextOutlined's repeated offset draws.


```lua
local length = #tbl
```
Reason: The length operator is the idiomatic and efficient choice for a sequential array-like table.


```lua
t = {}
```
Reason: Rebinding to a new empty table is generally faster because it avoids iterating over and deleting every entry in the existing table; use table.Empty(t) only when other references must see the same table cleared.


```lua
-- Slower: linear scan through a list
local allowed = { "admin", "moderator", "vip" }
if table.HasValue(allowed, rank) then
    -- allowed
end

-- Faster: set lookup
local allowedSet = {
    admin = true,
    moderator = true,
    vip = true,
}
if allowedSet[rank] then
    -- allowed
end
```
Reason: A keyed set lookup is typically O(1), while table.HasValue scans the list in O(n) time.


```lua
local playerData = {
    health = 100,
    armor = 50,
    alive = true,
}
```
Reason: Putting known fields directly in the table constructor avoids separate post-construction assignments and is generally faster.


```lua
local value = tbl[math.random(#tbl)]
```
Reason: A sequential table supports direct numeric indexing, avoiding table.Random's iteration overhead.


```lua
local squared = x * x
```
Reason: Direct multiplication is the simplest fast form for squaring in a tight loop.


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Visit ent here.
    end
end
```
Reason: `ents.Iterator()` traverses entities directly, so filtering by class does not first allocate a table of every entity.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers a uniquely identified callback that runs on every Think hook.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid checks that the reference exists and is not a removed entity before its methods are called.


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


```lua
local zeroAngle = angle_zero -- reuse; treat as read-only
```
Reason: Reusing Garry's Mod's predefined zero Angle avoids the allocation and constructor call from `Angle()`.


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


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP owns and synchronizes the job value through its DarkRPVar API, so use `getDarkRPVar("job")` instead of reading a generic networked string directly.


```lua
if positionA:DistToSqr(positionB) <= maxDistance * maxDistance then
    -- Within range
end
```
Reason: `Vector:DistToSqr` avoids the square-root calculation required for the actual distance.


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


```lua
local nearbyEntities = ents.FindInSphere(ply:GetPos(), 512)
```
Reason: ents.FindInSphere uses the engine’s spatial partition for a fast radius query and avoids the broader visibility semantics of FindInPVS.


```lua
local function FindPlayersNear(position, radius)
    local nearby = {}
    local radiusSquared = radius * radius
    local players = player.GetAll()

    for i = 1, #players do
        local ply = players[i]
        if position:DistToSqr(ply:GetPos()) <= radiusSquared then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```
Reason: Iterating only `player.GetAll()` avoids scanning every entity in the sphere, and squared-distance checks avoid square roots.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric for loops use specialized VM instructions and are generally faster than equivalent while loops.


Answer must contain 0 through 1 candidate loops.

```lua
-- Slower: one hook dispatch per player.
hook.Add("Tick", "CustomLogicPerPlayerSlow", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("CustomPlayerTickSlow", ply)
    end
end)

-- Faster: one hook dispatch; listeners loop over the player list.
hook.Add("Tick", "CustomLogicAllPlayersFast", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)

hook.Add("CustomPlayerTick", "RunCustomLogic", function(players)
    for _, ply in ipairs(players) do
        -- Custom per-player logic here.
    end
end)
```
Reason: Dispatching one hook per tick avoids repeating hook lookup and callback dispatch overhead for every player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache the health value once per HUDPaint call, avoiding two redundant LocalPlayer() lookups and Health() method calls.


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

for i = 1, itemCount do
    surface.SetDrawColor(WHITE)
    -- Draw item i.
end
```
Reason: Creating the color once avoids allocating a new Color object on every iteration.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

-- Hot path:
local function Think()
    if not IsValid(localPlayer) then return end

    local health = localPlayer:Health()
end
```
Reason: Cache LocalPlayer() once after the client entity exists, then reuse the reference in hot paths to avoid repeated lookups.


```lua
local FACING_DOT = 0.8 -- roughly within 37 degrees

local function AreLookingAtEachOther(a, b)
    local towardB = (b:EyePos() - a:EyePos()):GetNormalized()
    return a:GetAimVector():Dot(towardB) >= FACING_DOT
       and b:GetAimVector():Dot(towardB) <= -FACING_DOT
end
```
Reason: Dot products compare alignment directly against a precomputed threshold, avoiding the relatively expensive math.acos angle conversion.


```lua
SomeHelper(ply)
```
Reason: A plain function call usually avoids the per-call method lookup and implicit self handling of ply:SomeHelper(), so it is generally faster for a helper you control.


```lua
Msg("debug line\n")
```
Reason: `Msg` writes the preformatted string directly, avoiding `print`'s argument formatting overhead.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: Numeric for typically has the least iterator overhead and is fastest for a large sequential array-like table.


```lua
local players = player.GetAll()
local aliveNames = {}
local count = 0

for i = 1, #players do
    local ply = players[i]
    if ply:Alive() then
        count = count + 1
        aliveNames[count] = ply:Nick()
    end
end
```
Reason: A fused numeric loop avoids combinator closures and the intermediate table produced by separate filter and map passes.


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

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

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

hook.Add("Think", "ProcessCachedPlayers", function()
    for i = 1, cachedPlayerCount do
        local ply = cachedPlayers[i]
        -- Per-player work here.
    end
end)
```
Reason: The hot hook iterates a dense cached array, while the more expensive player lookup and cache mutation happen only on load, join, or disconnect.


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

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

local function GetPlayerData(ply)
    return playerData[ply]
end
```
Reason: A local Lua table avoids the Player userdata field/metamethod lookup, and weak keys discard entries after players become unreachable.


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

for i = 1, #values do
    local value = values[i]
end
```
Reason: A sequential number-indexed array supports a direct numeric loop, avoiding the hashing and generic-iterator overhead of string-keyed maps.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Separate numeric arguments avoid creating or unpacking a Color table on the hot draw path.


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


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

local function getSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID == nil then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: The weak-key cache computes each player's stable SteamID once without retaining disconnected player entities.


```lua
local pieces = {}

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

local result = table.concat(pieces)
```
Reason: Collecting pieces and calling table.concat once avoids repeatedly copying the entire growing string, reducing construction from roughly quadratic to linear work.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, avoiding the extra rounded-box helper overhead when the radius is zero.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(20, 20)
surface.DrawText("Fast single-line text")
```
Reason: Direct `surface.*` calls avoid the extra Lua work in `draw.DrawText` and the multiple offset draws required by `draw.SimpleTextOutlined`.


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


```lua
t = {}
```
Reason: Replacing the reference avoids iterating over and deleting every entry, so it is generally faster when no other code needs the original table emptied in place.


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

if allowed[userGroup] then
    -- Value exists in the set.
end
```
Reason: A keyed table lookup is typically O(1), while table.HasValue scans the list in O(n) time.


```lua
local data = {
    name = "example",
    count = 3,
    enabled = true,
}
```
Reason: Putting known fields directly in the table constructor avoids separate post-construction assignments and is generally faster.


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


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the overhead of exponentiation and is preferred in a tight loop.


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process ent here.
    end
end
```
Reason: `ents.Iterator()` traverses entities directly, avoiding the full entity table created by `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers a uniquely identified callback that runs on every Think hook.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid returns false for nil, NULL, removed, or otherwise invalid entity references, so method calls stay guarded.


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


```lua
local zeroAngle = angle_zero
```
Reason: `angle_zero` reuses Garry's Mod's shared zero Angle and avoids allocating a new `Angle()` on every hot-path call.


```lua
local configColor = Color(255, 255, 255)
local color = configColor
```
Reason: A local variable read avoids the global lookup and two table-key lookups required by `myaddon.config.color`.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP owns and synchronizes the job variable, so its accessor is preferred over reading the underlying networked string directly.


```lua
if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- Within range
end
```
Reason: `Vector:DistToSqr` avoids the square-root calculation required for the actual distance.


```lua
for ent in ents.Iterator() do
    -- Visit ent.
end
```
Reason: `ents.Iterator()` visits every entity directly and avoids allocating the table returned by `ents.GetAll()`.


```lua
local radius = 512
local origin = ply:GetPos()
local extent = Vector(radius, radius, radius)
local nearbyEntities = ents.FindInBox(origin - extent, origin + extent)
```
Reason: `ents.FindInBox` uses the engine’s spatial partition and is commonly faster than broader Lua-side filtering while providing a cheap axis-aligned proximity query.


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

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

    return nearby
end
```
Reason: Iterating only `player.GetAll()` avoids scanning unrelated entities, and squared-distance checks avoid a square root per player.


```lua
for i = 1, n do
    -- work
end
```
Reason: A numeric for loop generally uses fewer VM instructions than an equivalent while loop.


```lua
-- Faster: dispatch the custom hook once, then process every player.
hook.Add("Tick", "NotifyCustomLogic", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)

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

-- Slower pattern:
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("CustomPlayerTick", ply)
-- end
```
Reason: One hook.Run dispatch per tick avoids repeating hook lookup and callback dispatch overhead for every player.


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

    draw.SimpleText(health, "DermaLarge", 20, 20, color_white)
    draw.SimpleText(health, "DermaLarge", 20, 50, color_white)
    draw.SimpleText(health, "DermaLarge", 20, 80, color_white)
end)
```
Reason: Cache the health value once per HUDPaint call instead of repeating three Lua-to-engine method calls.


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

for i = 1, itemCount do
    surface.SetDrawColor(WHITE)
    -- draw item i
end
```
Reason: Create the color once outside the loop to avoid repeated table allocations and constructor calls.


```lua
local sin = math.sin

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


```lua
local cachedLocalPlayer

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

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

    -- Use ply here instead of repeatedly calling LocalPlayer().
end)
```
Reason: Cache the player once after client entities initialize, then reuse the local reference to avoid repeated global function calls and player lookups.


```lua
local FACING_DOT = -0.8 -- closer to -1 means more directly opposed

local function AimDirectionsFaceEachOther(playerA, playerB)
    return playerA:GetAimVector():Dot(playerB:GetAimVector()) <= FACING_DOT
end
```
Reason: A dot product directly compares the aim vectors against a precomputed cosine threshold, avoiding the expensive and unnecessary math.acos call.


```lua
SomeHelper(ply)
```
Reason: A local function call avoids the table/metatable lookup that `ply:SomeHelper()` performs, so it is generally faster.


```lua
Msg("debug line\n")
```
Reason: Msg writes the preformatted string directly, avoiding print's argument formatting overhead.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: A numeric for loop typically has the lowest iteration overhead for a large dense sequential table, outperforming ipairs and pairs.


```lua
local function filterMap(list, predicate, transform)
    local result = {}
    local resultCount = 0

    for index = 1, #list do
        local value = list[index]
        if predicate(value) then
            resultCount = resultCount + 1
            result[resultCount] = transform(value)
        end
    end

    return result
end
```
Reason: A fused numeric loop avoids the intermediate table, extra traversal, and combinator overhead of separate fn filter and map operations.


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

for index = 1, #cachedPlayers do
    playerIndexes[cachedPlayers[index]] = index
end

hook.Add("PlayerInitialSpawn", "PlayerCache.Add", function(ply)
    if playerIndexes[ply] then return end

    local index = #cachedPlayers + 1
    cachedPlayers[index] = ply
    playerIndexes[ply] = index
end)

hook.Add("PlayerDisconnected", "PlayerCache.Remove", function(ply)
    local index = playerIndexes[ply]
    if not index then return end

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

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

    if index ~= lastIndex then
        playerIndexes[lastPlayer] = index
    end
end)

hook.Add("Tick", "ProcessCachedPlayers", function()
    for index = 1, #cachedPlayers do
        local ply = cachedPlayers[index]
        -- Per-player work here.
    end
end)
```
Reason: The hot hook reuses a dense array, while join and leave hooks maintain it with O(1) insertion and removal instead of allocating and populating player.GetAll() every tick.


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

someFieldByPlayer[ply] = value
local value = someFieldByPlayer[ply]
```
Reason: A local Lua table keyed by the player avoids the slower Entity userdata field/metatable lookup on every read.


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

for i = 1, #values do
    local value = values[i]
end
```
Reason: Sequential number-indexed arrays support faster numeric iteration than string-keyed maps, which require hash traversal.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Separate numeric arguments avoid Color table creation and field lookups on the hot draw path.


```lua
local row = sql.QueryRow("SELECT credits FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64))
```
Reason: Local SQLite is typically lower latency because it runs in-process and avoids network round trips to a remote MySQL server.


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

local function getSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID == nil then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: A weak-key table replaces repeated engine method calls with cheap Lua table lookups without keeping disconnected player entities alive.


```lua
-- Slow: repeatedly copies the growing string.
local result = ""
for i = 1, 10000 do
    result = result .. tostring(i)
end

-- Faster: collect pieces, then join once.
local pieces = {}
for i = 1, 10000 do
    pieces[i] = tostring(i)
end
local fastResult = table.concat(pieces)
```
Reason: table.concat joins all pieces in one pass, avoiding the repeated copying and allocation caused by growing a string with .. inside the loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, avoiding the extra `draw.RoundedBox` wrapper work.


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

local text = "Single-line HUD text"

hook.Add("HUDPaint", "FastSingleLineText", function()
    SetFont("DermaDefault")
    SetTextColor(255, 255, 255, 255)
    SetTextPos(32, 32)
    DrawText(text)
end)
```
Reason: surface.DrawText avoids the wrapping, alignment, and outline work performed by draw.DrawText and draw.SimpleTextOutlined.


```lua
local length = #array
```
Reason: The length operator is the idiomatic and efficient choice for a sequential array-like table.


```lua
t = {}
```
Reason: Rebinding creates a new empty table in constant time, while table.Empty(t) must remove existing entries; use table.Empty only when other references must observe the same table being cleared.


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

if allowed[userGroup] then
    -- Value exists in the set.
end
```
Reason: A keyed set lookup is effectively O(1), while table.HasValue scans the list in O(n) time.


```lua
local data = {
    name = "example",
    count = 3,
    enabled = true,
}
```
Reason: Putting known fields directly in the constructor avoids separate post-creation assignments and is typically faster.


```lua
local value = items[math.random(#items)]
```
Reason: Sequential tables have dense numeric indices, so direct random indexing avoids the generic key-selection work performed by table.Random.


```lua
local squared = x * x
```
Reason: Multiplication is faster than exponentiation for squaring in a tight loop.


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process ent here.
    end
end
```
Reason: `ents.Iterator()` traverses entities directly, avoiding the full entity table allocated by `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: Registers the callback for each Think event under the unique identifier MyAddon.Think.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` confirms the reference exists and has not been removed before you call entity methods.


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


```lua
local zeroAngle = angle_zero -- Reuse; do not mutate.

local function hotPath()
    return zeroAngle
end
```
Reason: Reusing the built-in zero Angle avoids repeated userdata allocation and constructor overhead.


```lua
local addonColor = Color(255, 255, 255)
local color = addonColor
```
Reason: A local read avoids the two table lookups required by `myaddon.config.color` and is faster than reading a global.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP owns and synchronizes the `job` value through its DarkRPVar API, so use `getDarkRPVar` instead of accessing the underlying networked string directly.


```lua
local maxDistance = 500
if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- Within range.
end
```
Reason: Vector:DistToSqr avoids the unnecessary square root required to calculate the actual distance.


```lua
for ent in ents.Iterator() do
    -- Process ent.
end
```
Reason: `ents.Iterator()` visits every entity without allocating the table returned by `ents.GetAll()`, making it the wiki-recommended efficient choice.


```lua
local origin = ply:GetPos()
local extent = Vector(512, 512, 512)
local nearbyEntities = ents.FindInBox(origin - extent, origin + extent)
```
Reason: `ents.FindInBox` is commonly among the faster built-in spatial queries, trading spherical precision for a cheap axis-aligned lookup.


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

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

    return nearby
end
```
Reason: `player.Iterator()` scans only players without allocating a full player list, while `DistToSqr` avoids the square root used by ordinary distance checks.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` generally runs faster because Lua handles the counter, limit check, and increment internally.


```lua
-- Slower: repeats hook dispatch for every player.
local function notifyPerPlayer()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("CustomPlayerTick", ply)
    end
end

-- Faster: dispatches once; listeners process the player batch.
hook.Add("Tick", "NotifyCustomLogic", function()
    hook.Run("CustomPlayersTick", player.GetAll())
end)

hook.Add("CustomPlayersTick", "RunCustomLogic", function(players)
    for i = 1, #players do
        CustomLogic(players[i])
    end
end)
```
Reason: One batched hook.Run per tick avoids repeating hook lookup and listener-dispatch overhead for every player.


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

    draw.SimpleText(health, "DermaDefault", 20, 20, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 40, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 60, color_white)
end)
```
Reason: Cache the health value once per HUDPaint call, avoiding two redundant LocalPlayer() lookups and Health() method calls.


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

for i = 1, #items do
    surface.SetDrawColor(white)
    -- draw item
end
```
Reason: Allocate the color once outside the loop instead of creating a new Color object every iteration.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

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

    -- Use localPlayer here instead of calling LocalPlayer() repeatedly.
end)
```
Reason: Cache the player entity in a local upvalue after it becomes valid, so hot code performs a cheap local-variable read instead of repeated LocalPlayer() lookups.


```lua
local LOOK_DOT = 0.8 -- roughly within 37 degrees

local function AreLookingAtEachOther(a, b)
    local towardB = b:EyePos() - a:EyePos()
    towardB:Normalize()

    return a:GetAimVector():Dot(towardB) >= LOOK_DOT
       and b:GetAimVector():Dot(-towardB) >= LOOK_DOT
end
```
Reason: Dot products compare directly against a cosine threshold, avoiding the cost of math.acos while ensuring both players aim toward each other.


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

SomeHelper(ply)
```
Reason: A local function call generally avoids the entity/metatable method lookup required by `ply:SomeHelper()`.


```lua
Msg("debug line\n")
```
Reason: Msg avoids print's extra argument formatting and separator handling.


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- Use value.
end
```
Reason: A numeric for loop avoids the iterator-function overhead of pairs and ipairs, making it typically fastest for a dense sequential array.


```lua
local function getRichPlayerNames(players, minimumMoney)
    local names = {}
    local count = 0

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

        if money and money >= minimumMoney then
            count = count + 1
            names[count] = ply:Nick()
        end
    end

    return names
end
```
Reason: A fused numeric loop avoids combinator calls, closures, and the intermediate table that separate filter and map passes create.


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

for index, ply in ipairs(cachedPlayers) do
    playerIndexes[ply] = index
end

hook.Add("PlayerInitialSpawn", "PlayerCache.Add", function(ply)
    if playerIndexes[ply] then return end

    local index = #cachedPlayers + 1
    cachedPlayers[index] = ply
    playerIndexes[ply] = index
end)

hook.Add("PlayerDisconnected", "PlayerCache.Remove", function(ply)
    local index = playerIndexes[ply]
    if not index then return end

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

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

    if index ~= lastIndex then
        playerIndexes[lastPlayer] = index
    end
end)

hook.Add("Tick", "ProcessCachedPlayers", function()
    for index = 1, #cachedPlayers do
        local ply = cachedPlayers[index]
        -- Per-player tick work here.
    end
end)
```
Reason: The hot hook reuses one dense array, while rare join and leave events maintain it with constant-time insertion and removal.


```lua
local temporaryData = {}

temporaryData[ply] = value
local value = temporaryData[ply]

hook.Add("PlayerDisconnected", "ClearTemporaryData", function(disconnectedPlayer)
    temporaryData[disconnectedPlayer] = nil
end)
```
Reason: A local Lua table indexed by the player performs a direct table lookup and avoids the entity metatable lookup used by `ply.someField`.


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

for i = 1, #values do
    local value = values[i]
end
```
Reason: Sequential number-indexed arrays use Lua’s optimized array storage and avoid the hash traversal required by string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Separate numeric arguments avoid Color object creation and component lookup overhead on the hot path.


```lua
local result = sql.Query("SELECT credits FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64))
```
Reason: Local SQLite typically has lower latency because it avoids network round trips to a remote MySQL server.


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

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

    return steamID
end
```
Reason: A weak-key cache pays for `ply:SteamID()` once per player while allowing disconnected player objects to be garbage-collected.


```lua
-- Slow: allocates a new string on every iteration.
local slow = ""
for i = 1, 10000 do
    slow = slow .. tostring(i)
end

-- Fast: collect pieces, then join once.
local pieces = {}
for i = 1, 10000 do
    pieces[i] = tostring(i)
end
local fast = table.concat(pieces)
```
Reason: table.concat avoids repeatedly copying the entire growing string, reducing allocation and total work.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: surface.DrawRect draws a plain rectangle directly, avoiding draw.RoundedBox's wrapper overhead.


```lua
hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(24, 24)
    surface.DrawText("Single-line text")
end)
```
Reason: surface.DrawText draws the known single line directly, avoiding draw.DrawText’s multiline handling and SimpleTextOutlined’s extra outline draw calls.


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


```lua
t = {}
```
Reason: Replacing the reference avoids clearing every existing entry; use table.Empty(t) only when other references must observe the same table being emptied.


```lua
-- Slower: scans the entire list.
local allowedList = { "admin", "superadmin", "moderator" }
local isAllowedSlow = table.HasValue(allowedList, userGroup)

-- Faster: uses values as hash-table keys.
local allowedSet = {
    admin = true,
    superadmin = true,
    moderator = true,
}
local isAllowedFast = allowedSet[userGroup] == true
```
Reason: Direct key lookup is O(1) on average, while table.HasValue performs an O(n) linear scan.


```lua
local data = {
    name = "example",
    count = 3,
    enabled = true,
}
```
Reason: A table constructor initializes known fields directly, avoiding separate field-assignment operations after creating an empty table.


```lua
local randomElement = items[math.random(#items)]
```
Reason: Direct numeric indexing avoids table.Random's traversal overhead for sequential tables.


```lua
local squared = x * x
```
Reason: Multiplication avoids the overhead of the general-purpose exponentiation operator.


```lua
for ply in player.Iterator() do
    -- Use ply here.
end
```
Reason: player.Iterator() visits connected players directly without creating the table returned by player.GetAll().


```lua
local entity = ents.FindByClass("prop_physics")
for _, prop in ipairs(entity) do
    -- use prop
end
```
Reason: Garry's Mod does not expose a public lazy entity-class iterator; `ents.FindByClass` returns a table, so this cannot meet the stated constraint with documented Lua APIs.


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid` returns false for `nil`, invalid entity userdata, and entities that have been removed, so guard method calls with it.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here.
end)
```
Reason: `net.Receive` registers a server- or client-side callback for an incoming net message by name.


```lua
local zeroAngle = angle_zero

-- Hot path: reuse Garry's Mod's shared zeroed Angle instead of Angle()
entity:SetAngles(zeroAngle)
```
Reason: `angle_zero` avoids allocating and initializing a new Angle userdata on every call.


```lua
local myaddon_color = Color(255, 255, 255)
local color = myaddon_color
```
Reason: A local variable is faster to read than nested table indexing because it avoids table lookups; keep it scoped in a shared module rather than global when possible.


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

-- Avoid relying on the legacy networked-string key:
-- local jobName = ply:GetNWString("job")
```
Reason: DarkRP exposes the job through its DarkRPVar API, which is the supported abstraction and avoids depending on a legacy NWString key.


```lua
if posA:DistToSqr(posB) <= threshold * threshold then
    -- within threshold
end
```
Reason: `DistToSqr` avoids the square-root calculation required for actual distance.


```lua
for _, ent in ents.Iterator() do
    -- Use ent here.
end
```
Reason: `ents.Iterator()` is the wiki-recommended iterator for efficiently visiting every entity when you do not need a table from `ents.GetAll()`.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for nearby entities and is generally the practical default over PVS-based lookup for a fixed-radius search.


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

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

    return nearby
end
```
Reason: Iterating the player list avoids the broader entity spatial query and player filtering; squared-distance comparison avoids a square root per player.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric `for` is generally faster and clearer for a fixed 1-to-n count in Garry's Mod Lua.


```lua
-- Faster: one hook dispatch per tick; listeners handle every player.
hook.Run("CustomTickPlayers", player.GetAll())

hook.Add("CustomTickPlayers", "MyCustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Handle this player.
    end
end)

-- Slower: repeats hook lookup/dispatch for every player.
-- for i = 1, #player.GetAll() do
--     hook.Run("CustomTickPlayer", player.GetAll()[i])
-- end
```
Reason: A single hook dispatch avoids per-player hook lookup and callback iteration; iterate the player list inside each listener instead.


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

    draw.SimpleText("Health: " .. health, "DermaLarge", 20, 20, color_white)
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(20, 60, health * 2, 20)
    draw.SimpleText(health .. "%", "DermaDefault", 20, 85, color_white)
end)
```
Reason: Cache the player health once per frame and reuse the local value, avoiding two repeated Lua method calls.


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

for i = 1, count do
    surface.SetDrawColor(WHITE)
    -- paint work
end
```
Reason: Reusing one shared color avoids allocating a new Color object on every paint-loop iteration.


```lua
local sin = math.sin

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


```lua
-- Cache the function reference once, then reuse it.
local LocalPlayer = LocalPlayer

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

    -- use ply
end)
```
Reason: Localizing the global function avoids repeated global-table lookups while still retrieving the current LocalPlayer each call.


```lua
local function PlayersLookingAtEachOther(a, b, threshold)
    threshold = threshold or 0.7 -- 1 = directly facing; lower = more tolerant

    local aAim = a:GetAimVector()
    local bAim = b:GetAimVector()

    return aAim:Dot(bAim) <= -threshold
end
```
Reason: Unit aim vectors have a dot product near -1 when they point in opposite directions, avoiding the expensive inverse-cosine angle calculation.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the method lookup and implicit self argument setup, so they are generally faster for helpers you control.


```lua
Msg("debug line\n")
```
Reason: `Msg` writes directly to the console and avoids `print`’s extra argument conversion and formatting overhead.


```lua
for i = 1, #values do
    local value = values[i]
    -- use i and value
end
```
Reason: A numeric `for` directly indexes the sequential array and avoids the iterator-function overhead of `pairs` and `ipairs`.


```lua
-- Faster than chaining DarkRP.fn filter/map combinators: one loop, one output table.
local function activePlayerNames(players)
    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():upper()
        end
    end

    return names
end
```
Reason: This fuses filtering and mapping into one indexed loop, avoiding combinator callbacks and intermediate tables.


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

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

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

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- per-player tick work
    end
end)
```
Reason: `player.GetAll()` runs only when membership changes, while the hot Tick path reuses the cached array and iterates it with a numeric loop.


```lua
local playerValues = {}

-- write
playerValues[ply] = value

-- read
local value = playerValues[ply]
```
Reason: A plain Lua table indexed by the player avoids Garry's Mod entity-table field lookup overhead on frequent reads.


```lua
-- Faster for fixed ordered iteration: a sequential numeric array.
local values = {
    "alpha",
    "bravo",
    "charlie",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays use Lua’s array storage and support a tight indexed loop, while string-keyed maps require hash-table lookup and generic key iteration.


```lua
-- Hot path: pass channels directly; avoid constructing/reading a Color table.
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Separate numeric arguments avoid Color-object/table overhead in a frequently executed draw call.


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


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

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

-- Hot path:
local steamID = GetSteamIDCached(ply)

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIdCache[ply] = nil
end)
```
Reason: SteamIDs do not change during a player's connection, so caching avoids repeated Lua-to-engine method calls while weak keys allow departed player objects to be collected.


```lua
local pieces = {}

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

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

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


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: This avoids draw.RoundedBox’s helper-call overhead when no corner rounding is needed.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: Direct `surface.*` calls avoid the extra layout, alignment, and outline work performed by `draw.DrawText` and `draw.SimpleTextOutlined`.


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


```lua
-- Prefer replacing the reference when no other code retains this table.
t = {}
```
Reason: `t = {}` is generally faster because it avoids iterating through and clearing every existing entry; use `table.Empty(t)` only when other references must observe the same table being emptied.


```lua
-- Slower: scans every element in the list
if table.HasValue(allowedWeapons, weaponClass) then
    -- allowed
end

-- Faster: use a set for O(1)-average lookup
local allowedWeapons = {
    weapon_pistol = true,
    weapon_smg1 = true,
    weapon_shotgun = true,
}

if allowedWeapons[weaponClass] then
    -- allowed
end
```
Reason: `table.HasValue` performs a linear scan, while keyed set lookup is O(1) on average.


```lua
-- Faster for a small table with known fields: initialize it in the constructor.
local playerData = {
    name = "Iyda",
    score = 0,
    alive = true,
}

-- Less efficient: creates the table, then performs separate field assignments.
-- local playerData = {}
-- playerData.name = "Iyda"
-- playerData.score = 0
-- playerData.alive = true
```
Reason: A table constructor initializes the known fields as part of creation, avoiding separate post-creation assignment statements.


```lua
local value = items[math.random(#items)]
```
Reason: For a dense sequential table, direct indexed selection avoids `table.Random`'s extra work.


```lua
local squared = x * x
```
Reason: Multiplication avoids a function call and is the direct arithmetic operation for squaring.


```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() do
    if ent:GetClass() == "prop_physics" then
        -- Handle ent
    end
end
```
Reason: `ents.Iterator()` streams entities one at a time, avoiding construction of a full entity table.


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid` returns false for `nil`, invalid entities, and entities that have been removed, so it guards method calls safely.


```lua
net.Receive("MyAddon.Sync", function(length, sender)
    -- Handle the incoming message here.
end)
```
Reason: `net.Receive` registers a server- or client-side handler for incoming messages sent with `net.Start("MyAddon.Sync")`.


```lua
-- Reuse one zero Angle when the API only reads it.
local ZERO_ANGLE = angle_zero

-- Hot path:
entity:SetAngles(ZERO_ANGLE)

-- Avoid allocating a new Angle userdata each call:
-- entity:SetAngles(Angle(0, 0, 0))

-- If the callee may mutate it, pass a copy instead:
-- entity:SetAngles(Angle(ZERO_ANGLE))
```
Reason: `angle_zero` is Garry's Mod's shared zero-angle constant, so reusing it avoids repeated Angle userdata allocations; do not mutate the shared value.


```lua
local color = Color(255, 255, 255)
local currentColor = color
```
Reason: A local variable avoids table lookups, so it is faster for frequent reads; use a table only when namespacing or runtime configurability matters.


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

-- Avoid for job lookup: legacy/manual networked-string access
local oldJobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is DarkRP's job-state API and follows its own synchronization contract; `GetNWString` is a generic legacy networked-variable lookup and may not reflect DarkRP's intended data path.


```lua
if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- Within range
end
```
Reason: `DistToSqr` avoids the square-root calculation required for actual distance; compare it against the squared threshold.


```lua
for ent in ents.Iterator() do
    -- Use ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator for visiting every entity; use `ents.GetAll()` only when you need a reusable entity table.


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for nearby entities and avoids the broader visibility-driven behavior of `FindInPVS`.


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

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

    return found
end
```
Reason: Iterating `player.GetAll()` avoids scanning every entity, and squared-distance checks avoid square-root work.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric `for` loop is generally faster in Garry's Mod Lua because its counter, bound, and increment are handled by the VM rather than repeated Lua-level condition and increment operations.


```lua
-- Faster: one hook dispatch per tick; receivers iterate the supplied players.
local players = player.GetAll()
hook.Run("MyTickPlayers", players)

-- Slower: repeats hook lookup and dispatch once for every player.
for _, ply in ipairs(players) do
    hook.Run("MyTickPlayer", ply)
end
```
Reason: A single hook dispatch avoids repeating hook lookup and callback iteration for every player; pass the player list once and iterate it inside the hook receiver.


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

    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 20, color_white)
    draw.RoundedBox(4, 20, 40, health * 2, 16, Color(255, 0, 0))
    surface.DrawRect(20, 60, health * 2, 4)
end)
```
Reason: Cache the player health once per HUDPaint invocation and reuse it, avoiding two repeated Lua-to-engine method calls in the same frame.


```lua
local WHITE = color_white

for i = 1, count do
    surface.SetDrawColor(WHITE)
    -- paint work
end
```
Reason: Reusing Garry's Mod's shared `color_white` avoids allocating a new Color table on every iteration.


```lua
local sin = math.sin

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


```lua
local LocalPlayer = LocalPlayer

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

    -- Use player here.
end)
```
Reason: Caching the global function in a local upvalue avoids repeated global-table lookup while still retrieving the current local player each call.


```lua
local function AreRoughlyLookingAtEachOther(a, b, threshold)
    threshold = threshold or 0.7 -- higher means a tighter facing requirement

    local aAim = a:GetAimVector()
    local bAim = b:GetAimVector()

    return aAim:Dot(-bAim) >= threshold
end
```
Reason: Aim vectors are normalized, so their dot product directly measures opposing alignment without the expensive `math.acos` angle conversion.


```lua
SomeHelper(ply)
```
Reason: Passing `ply` to a plain/local helper avoids a metatable method lookup and is generally faster for helpers you control.


```lua
MsgN("debug line")
```
Reason: `MsgN` writes directly to the console and avoids `print`’s general-purpose argument formatting overhead for a fixed debug string.


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


```lua
-- Faster than chaining DarkRP.fn.Filter/Map: one pass, no intermediate tables.
local function activePlayerNames(players)
    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

    return names
end

local names = activePlayerNames(player.GetAll())
```
Reason: A single indexed loop avoids combinator closures, repeated traversal, and intermediate table allocation.


```lua
local cachedPlayers = {}

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

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

refreshPlayers()

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Per-player tick work.
        end
    end
end)
```
Reason: `player.GetAll()` only runs when the player roster changes, avoiding a new table allocation and roster lookup on every tick.


```lua
local PlayerValues = {}

-- Write
PlayerValues[ply] = value

-- Read
local value = PlayerValues[ply]
```
Reason: A module-local table lookup avoids the Player entity's Lua field access/metatable path, making repeated reads cheaper.


```lua
-- Faster for a fixed iterable collection: a dense, 1-based sequential array.
local values = {
    "alpha",
    "beta",
    "gamma",
}

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

-- Avoid a string-keyed map when iteration is the job:
-- local values = { first = "alpha", second = "beta", third = "gamma" }
-- for key, value in pairs(values) do end
```
Reason: A dense sequential array supports direct numeric indexing and predictable iteration, while string-keyed maps require hash lookups and are normally traversed with slower generic `pairs` iteration.


```lua
-- Faster in a hot path: avoid constructing/passing a Color table.
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numeric channels avoids Color-object/table handling on every draw call.


```lua
local row = sql.QueryRow("SELECT coins FROM player_data WHERE steamid = " .. sql.SQLStr(player:SteamID64()))
```
Reason: Local SQLite avoids network round trips, so it is typically lower latency for a single server with no cross-server synchronization need.


```lua
-- Cache per-player SteamIDs. Populate on join; clear on disconnect.
local steamIdByPlayer = {}

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

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

local function GetCachedSteamID(ply)
    local steamId = steamIdByPlayer[ply]
    if steamId then
        return steamId
    end

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

-- Hot path:
local steamId = GetCachedSteamID(ply)
```
Reason: It replaces repeated Lua-to-engine SteamID() calls with an O(1) table lookup and releases the player reference on disconnect.


```lua
local pieces = {}

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

-- Fast: one allocation/join pass.
local result = table.concat(pieces)

-- Slow for large strings: each .. creates a new string and copies prior content.
-- local result = ""
-- for i = 1, #pieces do
--     result = result .. pieces[i]
-- end
```
Reason: table.concat joins all pieces in one pass, avoiding the repeated allocations and growing copies caused by `..` in a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips `draw.RoundedBox`’s wrapper and corner-radius handling when no rounding is needed.


```lua
surface.SetFont("DermaDefault")
local text = "Status: Ready"
local color = Color(255, 255, 255)

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetTextColor(color)
    surface.SetTextPos(16, 16)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` once plus `surface.SetTextColor`/`SetTextPos`/`DrawText` avoids the extra alignment, outline, and convenience-layer work of `draw.DrawText` or `draw.SimpleTextOutlined` for fixed single-line text.


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


```lua
t = {}
```
Reason: Rebinding to a new empty table is generally faster because it avoids iterating over and clearing every existing entry; use it only when no other references need to observe the same table being emptied.


```lua
-- Slow: scans every element in the list (O(n))
local weapons = { "weapon_pistol", "weapon_smg1", "weapon_shotgun" }
if table.HasValue(weapons, "weapon_smg1") then
    print("found")
end

-- Fast: use a lookup set (average O(1))
local weaponSet = {
    weapon_pistol = true,
    weapon_smg1 = true,
    weapon_shotgun = true,
}

if weaponSet["weapon_smg1"] then
    print("found")
end
```
Reason: `table.HasValue` linearly scans a list, while keyed lookup uses Lua's hash table for average constant-time membership checks.


```lua
-- Faster for a small table with known fields: use the constructor.
local playerState = {
    health = 100,
    armor = 50,
    alive = true,
}

-- Slower:
-- local playerState = {}
-- playerState.health = 100
-- playerState.armor = 50
-- playerState.alive = true
```
Reason: The table constructor creates and initializes the known fields in one operation, avoiding separate table field assignments.


```lua
local value = values[math.random(#values)]
```
Reason: For a dense sequential table, indexing a uniformly random integer from 1 to `#values` avoids `table.Random`'s extra general-case handling.


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the overhead of a general-purpose power function in a tight loop.


```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 entity in ents.Iterator() do
    if entity:GetClass() == "prop_physics" then
        -- Use entity here.
    end
end
```
Reason: `ents.Iterator()` visits entities lazily, so no table containing every map entity is created.


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid(ent)` verifies the reference is a valid entity before calling entity methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here.
end)
```
Reason: `net.Receive` registers a server- or client-side callback for an incoming net message by name.


```lua
local ang = angle_zero
```
Reason: `angle_zero` reuses Garry's Mod's shared zero-angle constant, avoiding a new `Angle` allocation in the hot path; do not mutate it.


```lua
local myaddonColor = Color(255, 255, 255)
local color = myaddonColor
```
Reason: A flat local uses Lua’s fastest lookup path and avoids the extra table field lookup; avoid globals because they are slower and can collide.


```lua
-- Preferred in DarkRP: uses DarkRP's authoritative job table.
local jobName = team.GetName(ply:Team())

-- Avoid for job lookup:
local networkedJobName = ply:GetNWString("job")
```
Reason: `team.GetName(ply:Team())` reads the player’s current DarkRP team/job directly, while the networked `job` string is legacy replicated state and can be absent or stale.


```lua
if posA:DistToSqr(posB) <= threshold * threshold then
    -- vectors are within the threshold
end
```
Reason: `DistToSqr` avoids the unnecessary square-root calculation performed by `Distance`.


```lua
for _, entity in ents.Iterator() do
    -- Visit entity
end
```
Reason: `ents.Iterator()` avoids allocating the table that `ents.GetAll()` creates, so it is the preferred iterator when you only need to visit each entity once.


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for entities within a radius of the player.


```lua
-- player.GetAll() is cached by the engine; avoid allocating a broad entity list.
local function FindPlayersNear(pos, radius)
    local radiusSqr = radius * radius
    local nearby = {}

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

    return nearby
end
```
Reason: Iterating the player-only list avoids `ents.FindInSphere`'s broad entity query and filtering, while squared-distance checks avoid per-player square roots.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric `for` loop is generally faster and clearer in Garry's Mod Lua because its counter, bound, and increment are handled by the VM.


```lua
-- Faster: one hook dispatch, all players passed as data.
hook.Run("MyAddonTickPlayers", player.GetAll())

-- Slower: repeats hook lookup and dispatch once per player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyAddonTickPlayer", ply)
end
```
Reason: One `hook.Run` performs the hook dispatch once; per-player handlers can iterate the supplied player list without repeating that dispatch for every player.


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

    draw.SimpleText(health, "DermaLarge", 20, 20)
    surface.DrawRect(20, 50, health, 12)
    draw.SimpleText("HP: " .. health, "DermaDefault", 20, 70)
end)
```
Reason: Cache the per-frame health value once and reuse it, avoiding two redundant player method calls.


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

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


```lua
local sin = math.sin

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


```lua
local LocalPlayer = LocalPlayer

hook.Add("Think", "Example", function()
    local player = LocalPlayer()
    -- use player
end)
```
Reason: Caching the global function in a local avoids repeated global-table lookups while still retrieving the current local player when needed.


```lua
local function AreRoughlyLookingAtEachOther(playerA, playerB, threshold)
    threshold = threshold or 0.7
    return playerA:GetAimVector():Dot(playerB:GetAimVector()) <= -threshold
end
```
Reason: Aim vectors are normalized, so their dot product is a cheap comparison that becomes negative when they face opposite directions; this avoids the expensive inverse cosine calculation.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid method lookup through the player/metatable and are generally faster for helpers you control.


```lua
MsgN("debug line")
```
Reason: `MsgN` writes directly to the console and avoids `print`'s extra formatting work.


```lua
for i = 1, #values do
    local value = values[i]
    -- use i and value
end
```
Reason: A numeric `for` avoids the iterator-function overhead of `pairs` and `ipairs`; for a dense sequential array, it is typically the fastest of these options.


```lua
-- Faster than chaining DarkRP.fn.Filter/Map: one indexed pass, no intermediate tables.
local function activePlayerNames(players)
    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

    return names
end
```
Reason: A single indexed loop avoids combinator callback overhead and the intermediate table created between filter and map steps.


```lua
local players = {}

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

hook.Add("PlayerInitialSpawn", "RefreshCachedPlayersOnJoin", function()
    refreshPlayers()
end)

hook.Add("PlayerDisconnected", "RefreshCachedPlayersOnLeave", function()
    refreshPlayers()
end)

hook.Add("Think", "UseCachedPlayers", function()
    for i = 1, #players do
        local ply = players[i]
        -- Per-player tick work here.
    end
end)

refreshPlayers()
```
Reason: `player.GetAll()` allocates/builds the player list only on join or disconnect, while the hot hook iterates the cached array each tick.


```lua
local playerData = setmetatable({}, { __mode = "k" }) -- weak keys: data dies with the player

-- Write
playerData[ply] = value

-- Read (faster than a Lua entity field lookup)
local value = playerData[ply]
```
Reason: A Lua table keyed by the player avoids Garry's Mod Entity userdata field access on every read.


```lua
-- Faster for fixed-value iteration: a sequential, 1-based array.
local values = {
    "alpha",
    "beta",
    "gamma",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential integer keys use Lua's array part and support a tight numeric loop, avoiding hash lookup and unordered map traversal.


```lua
-- Hot path: avoid allocating or unpacking a Color table each draw.
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate channel numbers avoids the Color-object/table argument path and is the lower-overhead style for repeated draw calls.


```lua
local row = sql.QueryRow("SELECT value 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 without cross-server synchronization.


```lua
local steamIdCache = setmetatable({}, { __mode = "k" }) -- weak keys: players can be collected

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

-- Hot path:
local steamId = CachedSteamID(ply)
```
Reason: SteamID is stable for a connected player, so caching avoids repeated Lua-to-engine method calls while weak player keys prevent stale cache entries from retaining players.


```lua
local parts = {}

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

local largeString = table.concat(parts)
```
Reason: `table.concat` joins the pieces in one pass, avoiding the repeated allocations and copying caused by growing a string with `..` inside the loop.


```lua
surface.DrawRect(x, y, w, h)
```
Reason: It draws the rectangle directly and avoids `draw.RoundedBox`'s wrapper overhead when no corner rounding is needed.


```lua
-- Cache the font once (for example in a client initialization hook).
surface.CreateFont("HUD.FastText", {
    font = "Roboto",
    size = 22,
    weight = 500,
    antialias = true,
})

-- Per frame: surface calls avoid draw.DrawText/SimpleTextOutlined helper overhead.
surface.SetFont("HUD.FastText")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(24, 24)
surface.DrawText("Single-line HUD text")
```
Reason: `surface.SetFont` + `surface.SetTextColor` + `surface.SetTextPos` + `surface.DrawText` is the leaner direct path for plain single-line text; use `draw.SimpleTextOutlined` only when the outline is visually required.


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


```lua
-- Fastest when no other code needs to keep the same table object:
t = {}
```
Reason: `t = {}` allocates a new empty table, while `table.Empty(t)` must visit and remove the existing entries; use `table.Empty(t)` only when other references must observe the same table being cleared.


```lua
-- Slower: linear scan through an array/list
local allowed = { "admin", "moderator", "vip" }
if table.HasValue(allowed, player:GetUserGroup()) then
    -- allowed
end

-- Faster: use the values as keys for O(1) average lookup
local allowedSet = {
    admin = true,
    moderator = true,
    vip = true,
}

if allowedSet[player:GetUserGroup()] then
    -- allowed
end
```
Reason: table.HasValue scans the list linearly, while a key lookup in a set is O(1) on average.


```lua
-- Faster for a small table with known fields:
local playerData = {
    name = "Iyda",
    score = 0,
    active = true,
}

-- Rather than:
-- local playerData = {}
-- playerData.name = "Iyda"
-- playerData.score = 0
-- playerData.active = true
```
Reason: The table constructor creates and initializes the known fields in one expression, avoiding separate field-assignment operations.


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


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the overhead of a general exponentiation call in a tight loop.


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


```lua
for _, entity in ents.Iterator() do
    if entity:GetClass() == "prop_physics" then
        -- Use entity here.
    end
end
```
Reason: `ents.Iterator()` iterates entities directly instead of materializing all map entities in a table.


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid(ent)` returns true only while `ent` refers to a valid entity, preventing method calls on invalid or removed entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Read payload here with net.Read* functions.
end)
```
Reason: `net.Receive` registers a server-side handler for incoming messages with that name.


```lua
local workAngle = Angle()

-- Hot path: reuse the same Angle when it will not escape this scope.
workAngle:Zero()
```
Reason: `:Zero()` resets an existing Angle and avoids the allocation and garbage-collection cost of constructing `Angle()` each iteration.


```lua
local myaddon_color = Color(255, 255, 255)
local color = myaddon_color
```
Reason: A local variable avoids the extra table lookups required by `myaddon.config.color` and is the fastest option for frequent reads.


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

-- Avoid for DarkRP job state:
-- local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` reads DarkRP’s supported job variable and avoids relying on legacy networked-string state.


```lua
if a:DistToSqr(b) <= threshold * threshold then
    -- vectors are within the threshold
end
```
Reason: `DistToSqr` avoids the unnecessary square-root calculation performed when computing the actual distance.


```lua
for _, ent in ents.Iterator() do
    -- Use ent
end
```
Reason: `ents.Iterator()` visits entities without allocating the table that `ents.GetAll()` creates, so it is the efficient wiki-recommended choice for a simple full-entity loop.


```lua
local nearbyEntities = ents.FindInSphere(player:GetPos(), 512)
```
Reason: `ents.FindInSphere` uses the engine’s spatial query instead of scanning every entity, making it a fast general-purpose nearby-entity lookup.


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

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

    return players
end
```
Reason: Iterating only players avoids scanning every entity, and squared-distance checks avoid the square root used by distance calculations.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric `for` loop is generally the faster and clearer counting-loop primitive in Garry's Mod Lua.


```lua
-- Faster: one hook dispatch; listeners receive the whole player list.
hook.Run("MyCustomTick", player.GetAll())

-- Slower: one hook dispatch for every player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomTick", ply)
end
```
Reason: Dispatching the hook once avoids repeated hook lookup and listener calls for every player.


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

draw.RoundedBox(4, 20, 20, health * 2, 24, Color(220, 60, 60))
draw.SimpleText(health, "DermaDefault", 24, 24, color_white)
draw.SimpleText("HP: " .. health, "DermaDefault", 24, 52, color_white)
```
Reason: Cache `LocalPlayer():Health()` once per HUDPaint frame to avoid two repeated player-method calls.


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

for i = 1, count do
    surface.SetDrawColor(WHITE)
    -- draw
end
```
Reason: Reusing one color avoids allocating a new Color object on every paint-loop iteration.


```lua
local sin = math.sin

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


```lua
local localPlayer

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

-- Hot path:
if IsValid(localPlayer) then
    local health = localPlayer:Health()
end
```
Reason: Cache the player entity after client entities initialize, so hot paths reuse a local reference instead of repeatedly calling `LocalPlayer()`.


```lua
local function AreLookingAtEachOther(a, b)
    return a:GetAimVector():Dot(b:GetAimVector()) <= -0.75
end
```
Reason: The dot product is near -1 when two normalized aim vectors point in opposite directions, avoiding the expensive `math.acos` angle calculation.


```lua
SomeHelper(ply)
```
Reason: A direct helper call avoids the player metatable method lookup that `ply:SomeHelper()` performs.


```lua
MsgN("debug: hot path reached")
```
Reason: `MsgN` writes directly to the Garry's Mod console and avoids `print`’s extra Lua output handling.


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


```lua
-- Filter active players and map them to SteamIDs in one pass.
-- Faster than chaining fn.Filter(...)(players) then fn.Map(...)(result).
local function activeSteamIDs(players)
    local steamIDs = {}
    local count = 0

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

        if IsValid(ply) and ply:Alive() then
            count = count + 1
            steamIDs[count] = ply:SteamID()
        end
    end

    return steamIDs
end

local steamIDs = activeSteamIDs(player.GetAll())
```
Reason: A numeric loop fuses the filter and map into one pass, avoiding combinator callbacks and an intermediate table.


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

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

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

hook.Add("Tick", "MyAddon.ProcessPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Per-player tick work.
    end
end)
```
Reason: `player.GetAll()` now runs only on join and leave events, while Tick iterates the cached array directly.


```lua
local temporaryData = {}

temporaryData[ply] = value

local value = temporaryData[ply]

hook.Add("PlayerDisconnected", "ClearTemporaryPlayerData", function(ply)
    temporaryData[ply] = nil
end)
```
Reason: An ordinary Lua table keyed by the player bypasses the Player entity metatable’s dynamic field lookup, making repeated reads cheaper; clear it on disconnect to avoid retaining player references.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential numeric indices form Lua’s array part, enabling faster indexed iteration than hash-based string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255)
```
Reason: Passing separate numeric channels avoids Color object allocation and lookup overhead in a hot draw path.


```lua
local rows = sql.Query("SELECT value FROM player_data WHERE steamid = " .. sql.SQLStr(steamID))
```
Reason: Local SQLite typically has lower read/write latency on one server because it avoids remote network round trips and MySQL connection overhead.


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

local function CachedSteamID(ply)
    local steamId = steamIdCache[ply]
    if not steamId then
        steamId = ply:SteamID()
        steamIdCache[ply] = steamId
    end
    return steamId
end

-- Hot path:
local steamId = CachedSteamID(ply)
```
Reason: SteamID values are immutable per player, so this replaces repeated native method calls with a cheap table lookup while weak keys avoid retaining disconnected players.


```lua
local parts = {}

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

local result = table.concat(parts)
```
Reason: `table.concat` joins the pieces once, avoiding the repeated string allocations and copies caused by growing a string with `..` in a loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, width, height)
```
Reason: It avoids `draw.RoundedBox`'s wrapper and directly issues the rectangle draw.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(24, 24)
surface.DrawText("Status: ready")
```
Reason: Direct surface text calls avoid the extra alignment, font, color, and outline work performed by draw.DrawText and draw.SimpleTextOutlined.


```lua
local length = #items
```
Reason: `#` is the idiomatic Lua length operator for sequential array-like tables.


```lua
t = {}
```
Reason: `t = {}` replaces the table in constant time, while `table.Empty(t)` iterates through and removes every existing entry; only use replacement when other code does not need to retain the same table reference.


```lua
-- Slow for repeated lookups: table.HasValue({ "admin", "moderator" }, role)
local allowedRoles = {
    admin = true,
    moderator = true,
    user = true,
}

if allowedRoles[role] then
    -- role exists in the set
end
```
Reason: Key lookup is typically O(1), while table.HasValue scans the list in O(n).


```lua
-- Faster: create and populate the table in one constructor.
local playerInfo = {
    name = "Alyx",
    score = 42,
    alive = true,
}

-- Slower:
-- local playerInfo = {}
-- playerInfo.name = "Alyx"
-- playerInfo.score = 42
-- playerInfo.alive = true
```
Reason: A table constructor initializes the known fields during creation, avoiding separate field-assignment operations.


```lua
local element = items[math.random(#items)]
```
Reason: It indexes the array directly using its cached-length operator, avoiding table.Random’s general-purpose table handling.


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


```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() do
    if ent:GetClass() == "prop_physics" then
        -- Visit ent here.
    end
end
```
Reason: ents.Iterator() traverses entities incrementally instead of creating an all-entities table.


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid(ent)` verifies that the entity reference exists and has not been removed before methods are called.


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


```lua
-- Use this when the Angle will only be read/passed through.
local ang = angle_zero
```
Reason: `angle_zero` is Garry's Mod's preallocated zero Angle, avoiding `Angle()` allocation and constructor overhead; never mutate the shared value.


```lua
local MYADDON_COLOR = Color(255, 255, 255)
local color = MYADDON_COLOR
```
Reason: A local variable is faster to read than a nested table lookup; avoid globals on hot paths.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: `getDarkRPVar` is DarkRP’s supported accessor for its synchronized job variable.


```lua
if vectorA:DistToSqr(vectorB) <= threshold * threshold then
    -- vectors are within 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
end
```
Reason: `ents.Iterator()` avoids allocating the table created by `ents.GetAll()`.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: `ents.FindInSphere` is a fast engine spatial query for entities within a radius around the player.