```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 table allocation performed 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 is non-nil and refers to an entity that has not been removed.


```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 ZERO_ANGLE = Angle(0, 0, 0)

-- Hot path: copy the cached angle instead of calling Angle() again.
local ang = ZERO_ANGLE * 1
```
Reason: Copying a cached zero Angle avoids the repeated global lookup and constructor-call overhead of creating it with Angle() each time.


```lua
local color = Color(255, 255, 255)
local currentColor = color
```
Reason: A local variable is faster to read than nested table fields because it avoids global and repeated 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: DistToSqr avoids the square root required for actual distance, making threshold comparisons faster.


```lua
for ent in ents.Iterator() do
    -- Use ent here
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient way to visit every entity without creating the intermediate table returned by `ents.GetAll()`.


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


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

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

    return nearby
end
```
Reason: Iterating `player.GetAll()` checks only players, and `DistToSqr` avoids the square root and the larger entity scan performed by `ents.FindInSphere`.


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


```lua
hook.Add("Tick", "NotifyPlayers", function()
    hook.Run("NotifyCustomLogic", player.GetAll())
end)
```
Reason: One hook.Run per tick avoids repeated hook dispatch overhead for every player.


```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() lookups and Health() method calls.


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

for i = 1, #items do
    drawItem(items[i], white)
end
```
Reason: Create the Color once outside the hot loop to avoid repeated table allocation and constructor work.


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

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 variable after entities initialize avoids repeated global function calls and LocalPlayer lookups.


```lua
local FACE_DOT = 0.8 -- Higher means stricter alignment.

local function AreRoughlyLookingAtEachOther(a, b)
    local direction = b:EyePos() - a:EyePos()
    direction:Normalize()

    return a:GetAimVector():Dot(direction) >= FACE_DOT
       and b:GetAimVector():Dot(direction) <= -FACE_DOT
end
```
Reason: Dot products compare both aim vectors against one normalized player-to-player direction, avoiding the cost of `math.acos` and angle construction.


```lua
SomeHelper(ply)
```
Reason: It generally avoids the metatable method lookup that `ply:SomeHelper()` requires, so a controlled helper is usually marginally faster.


```lua
MsgN("debug line")
```
Reason: MsgN writes directly to the console without print's extra argument formatting and tab-separated output handling.


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


```lua
local result = {}
local resultCount = 0

for i = 1, #players do
    local ply = players[i]
    if ply:isAlive() then
        resultCount = resultCount + 1
        result[resultCount] = ply:Nick()
    end
end
```
Reason: One plain loop fuses filtering and mapping, avoiding fn combinator calls, intermediate tables, and extra allocations.


```lua
local cachedPlayers = {}

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

hook.Add("Initialize", "BuildPlayerCache", rebuildPlayerCache)
hook.Add("PlayerInitialSpawn", "RefreshPlayerCacheOnJoin", rebuildPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", function(leavingPlayer)
    for index = #cachedPlayers, 1, -1 do
        if cachedPlayers[index] == leavingPlayer then
            table.remove(cachedPlayers, index)
            break
        end
    end
end)

hook.Add("Tick", "ProcessCachedPlayers", function()
    for index = 1, #cachedPlayers do
        local ply = cachedPlayers[index]
        if IsValid(ply) then
            -- Per-player tick work.
        end
    end
end)
```
Reason: The tick path reuses one cached array, avoiding a fresh player.GetAll() result and ipairs iterator setup every tick while join and leave hooks keep membership current.


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

playerData[ply] = value
local value = playerData[ply]
```
Reason: Reading a local Lua table avoids the Player userdata’s metatable lookup, while weak keys automatically release entries after players become unreachable.


```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, avoiding hash-key traversal.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing separate numeric channels avoids Color object creation and table field lookups in the hot draw path.


```lua
local result = sql.Query("SELECT * 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: A weak-key cache calls `SteamID()` once per player entity and automatically releases entries after disconnected player entities are collected.


Answer must contain 0 through 0 candidate loops.

```lua
local pieces = {}

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

local result = table.concat(pieces)
```
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.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 corner 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.SetTextPos plus surface.DrawText avoids the extra alignment, newline, and outline work performed by draw.DrawText and draw.SimpleTextOutlined.


```lua
local length = #tbl
```
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 than iterating through the old table to remove every entry, provided no other references need that same table emptied.


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

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


```lua
local playerData = {
    health = 100,
    armor = 50,
    alive = true,
}
```
Reason: Putting known fields in the table constructor is faster because Lua creates and initializes the table in one operation instead of performing separate field assignments.


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


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


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

```lua
for ply in player.Iterator() do
    -- Use ply here.
end
```
Reason: `player.Iterator()` visits each currently connected player 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 without first allocating the full 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.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid checks that ent exists and has not been removed before a method is 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 is received.


```lua
local ZERO_ANGLE = angle_zero

-- Hot path:
local ang = ZERO_ANGLE
```
Reason: Reusing Garry's Mod's built-in immutable-by-convention `angle_zero` avoids allocating and initializing a new `Angle()` userdata on every call.


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


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP job data is exposed through `getDarkRPVar`; using it preserves DarkRP’s data contract 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 actual distance.


```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 efficient choice when only iteration is needed.


```lua
local nearbyEntities = ents.FindInSphere(player:GetPos(), 512)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query that directly returns entities within a radius.


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

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

    return nearby
end
```
Reason: Iterating players directly avoids scanning unrelated entities, and squared-distance checks avoid a square root for every player.


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


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


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

draw.SimpleText(health, "DermaDefault", 10, 10, color_white)
draw.SimpleText(health, "DermaDefault", 10, 30, color_white)
draw.SimpleText(health, "DermaDefault", 10, 50, color_white)
```
Reason: Cache the health value once per HUDPaint call to avoid two redundant LocalPlayer() lookups and Health() method calls.


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

for i = 1, count do
    drawItem(i, white)
end
```
Reason: Creating the color once outside the paint loop avoids repeated table allocation and garbage-collection work.


```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 = LocalPlayer()

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

local function GetLocalPlayer()
    return localPlayer
end
```
Reason: Cache the player once after client entities initialize, so hot-path calls become a cheap local-variable read.


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

local function AreLookingAtEachOther(a, b)
    local offset = b:EyePos() - a:EyePos()
    if offset:IsZero() then return false end

    local direction = offset:GetNormalized()
    return a:GetAimVector():Dot(direction) >= FACE_DOT
       and b:GetAimVector():Dot(-direction) >= FACE_DOT
end
```
Reason: Dot products compare alignment directly against a precomputed cosine threshold, avoiding the extra cost of `math.acos` and angle construction.


```lua
SomeHelper(ply)
```
Reason: It is generally faster because it avoids metatable method lookup and passes `ply` directly, though the difference is usually small.


```lua
Msg("debug line\n")
```
Reason: Msg writes the string directly without print's argument formatting and separator handling.


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


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

for i = 1, #players do
    local ply = players[i]
    if ply:isArrested() then
        count = count + 1
        output[count] = ply:Nick()
    end
end
```
Reason: One fused numeric loop avoids fn combinator callbacks and intermediate tables while producing the same filtered-and-mapped list.


```lua
local cachedPlayers = {}

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

hook.Add("Initialize", "RefreshPlayerCache", refreshPlayerCache)
hook.Add("PlayerInitialSpawn", "RefreshPlayerCacheOnJoin", refreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", function(leavingPlayer)
    for index = #cachedPlayers, 1, -1 do
        if cachedPlayers[index] == leavingPlayer then
            table.remove(cachedPlayers, index)
            break
        end
    end
end)

hook.Add("Tick", "ProcessCachedPlayers", function()
    for index = 1, #cachedPlayers do
        local ply = cachedPlayers[index]
        if IsValid(ply) then
            -- Per-player tick work here.
        end
    end
end)
```
Reason: This avoids rebuilding the player list every tick; joins refresh the snapshot, leaves remove the departing player immediately, and the hot loop uses a numeric array traversal.


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

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

local function GetTemporaryData(ply)
    return playerData[ply]
end
```
Reason: A local Lua table keyed by player avoids repeated userdata/metatable field lookup, while weak keys let disconnected players be garbage-collected.


```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 and avoid the overhead of `pairs` and hash-key lookup.


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing separate RGBA numbers avoids the Color-object overload and is faster on a hot draw path.


```lua
local row = sql.QueryRow("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 GetCachedSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID == nil then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: Weak player keys avoid retaining disconnected players, while each live player's SteamID is computed only once.


```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 copying the growing string.


```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 corner radius is zero.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(20, 20)
surface.DrawText("Fast single-line text")
```
Reason: `surface.DrawText` is the leanest direct helper for one line; `draw.DrawText` adds multiline handling, while `draw.SimpleTextOutlined` performs extra draw calls for the outline.


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


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


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

if valueSet[targetValue] then
    -- Value exists in the set.
end
```
Reason: A keyed set uses an average O(1) table lookup, while table.HasValue scans the list in O(n) time.


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


```lua
local value = values[math.random(#values)]
```
Reason: For a sequential table, direct random indexing avoids table.Random's generic key iteration and is therefore faster.


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


```lua
for ply in player.Iterator() do
    -- Use ply here.
end
```
Reason: `player.Iterator()` visits each connected player directly without creating the temporary 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 without first allocating a table containing 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 ent exists and has not been removed before its methods are called.


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


```lua
local zeroAngle = angle_zero -- Reuse; do not mutate this shared Angle.
```
Reason: Reusing the engine-provided `angle_zero` avoids allocating and constructing a new `Angle()` on every hot-path call.


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


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


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


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


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


```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 ply:GetPos():DistToSqr(position) <= radiusSqr then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```
Reason: Iterating the small player list directly avoids scanning every entity in the sphere, and squared distance avoids 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 `while` loop is generally faster than a numeric `for` loop for tight counting.


```lua
hook.Add("Tick", "NotifyCustomLogic", function()
    hook.Run("CustomLogicTick", player.GetAll())
end)
```
Reason: Calling hook.Run once per tick avoids repeated hook dispatch overhead; listeners can loop through 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 player lookup and method calls.


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

for i = 1, count do
    drawSomething(items[i], WHITE)
end
```
Reason: Create the Color once outside the hot loop to avoid allocating and initializing the same value 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 table lookups inside the hot loop.


```lua
local localPlayer

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

hook.Add("Think", "Example", function()
    if IsValid(localPlayer) then
        local position = localPlayer:GetPos()
    end
end)
```
Reason: Cache the player entity once after initialization so hot paths reuse a local variable instead of repeatedly calling the global LocalPlayer() lookup.


```lua
local facingDot = 0.8 -- Higher means stricter; 0.8 is roughly within 37 degrees.

local function AreLookingAtEachOther(a, b)
    local direction = (b:EyePos() - a:EyePos()):GetNormalized()

    return a:GetAimVector():Dot(direction) >= facingDot
       and b:GetAimVector():Dot(-direction) >= facingDot
end
```
Reason: Dot products compare aim alignment directly against a precomputed threshold, avoiding the cost of math.acos and angle construction.


```lua
SomeHelper(ply)
```
Reason: A direct function call generally avoids the metatable method lookup performed by `ply:SomeHelper()`; the implicit `self` argument itself has no meaningful extra cost.


```lua
Msg("Debug line\n")
```
Reason: Msg avoids print's extra argument formatting and is faster for a preformatted string.


```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 results = {}
local count = 0

for i = 1, #jobs do
    local job = jobs[i]
    if job.salary >= minimumSalary then
        count = count + 1
        results[count] = string.lower(job.name)
    end
end
```
Reason: One fused numeric loop avoids fn callback overhead and the intermediate table normally created between filter and map.


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

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

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

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

hook.Add("PlayerDisconnected", "PlayerCache.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 i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Per-player tick work here.
    end
end)
```
Reason: This removes the per-tick `player.GetAll()` allocation and uses O(1) join, lookup, and swap-removal while keeping the cached table dense for fast numeric iteration.


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

local function SetTemporaryData(ply, value)
    temporaryData[ply] = value
end

local function GetTemporaryData(ply)
    return temporaryData[ply]
end
```
Reason: A local Lua table lookup avoids the Player userdata metatable (`__index`) path used by `ply.someField`, and weak keys prevent stale player references from being retained.


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

for index = 1, #values do
    local value = values[index]
    -- use value
end
```
Reason: Sequential number-indexed arrays use Lua’s optimized array storage and a numeric loop avoids the hashing and iterator overhead of string-keyed maps.


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


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64) .. " LIMIT 1")
```
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: Weak player keys avoid repeated engine calls 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 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 and avoids the extra `draw.RoundedBox` wrapper work.


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


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


```lua
t = {}
```
Reason: Rebinding creates a fresh empty table in constant time, while table.Empty(t) must remove the existing entries one by one.


```lua
-- Slower: linear scan through a list
local allowed = { "admin", "moderator", "developer" }
local isAllowed = table.HasValue(allowed, userGroup)

-- Faster: direct lookup in a set
local allowedSet = {
    admin = true,
    moderator = true,
    developer = true,
}
local isAllowedFast = allowedSet[userGroup] == true
```
Reason: A set-style table uses an average O(1) key lookup, while table.HasValue scans the list in O(n) time.


```lua
local data = {
    name = "Gordon",
    health = 100,
    alive = true,
}
```
Reason: A table constructor initializes known fields directly and avoids separate assignment operations after creating an empty table.


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


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


```lua
for _, ply in player.Iterator() do
    -- Use ply here.
end
```
Reason: player.Iterator() traverses the currently connected players directly without creating 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, avoiding the table allocation performed by `ents.GetAll()` or `ents.FindByClass()`.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid` checks that the reference exists and, for entities, has not been removed before you call its methods.


```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 zero = angle_zero -- Reuse; do not mutate.
```
Reason: `angle_zero` avoids the allocation and constructor call performed by `Angle()`.


```lua
local addonColor = Color(255, 255, 255)
local color = addonColor
```
Reason: A local variable avoids global lookup and nested table indexing, so it is fastest for a frequently read setting.


```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 required for the actual distance, making threshold comparisons faster.


```lua
for ent in ents.Iterator() do
    -- Visit ent.
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator and avoids allocating the table returned by `ents.GetAll()`.


```lua
local position = player:GetPos()
local radius = 512
local nearbyEntities = ents.FindInSphere(position, radius)
```
Reason: `ents.FindInSphere` uses Garry's Mod's built-in spatial partition and is typically much cheaper than scanning `ents.GetAll()` and calculating distances 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 position:DistToSqr(ply:GetPos()) <= radiusSquared then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```
Reason: Iterating the player list avoids scanning nearby non-player entities, and squared-distance checks avoid a square root for every player.


```lua
for i = 1, n do
    -- work
end
```
Reason: A numeric for loop generally has less interpreter overhead than an equivalent while loop in Garry's Mod Lua.


```lua
-- Faster: dispatch once per tick with the player list.
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 logic for ply.
    end
end)

-- Slower: dispatches the hook once for every player.
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("CustomPlayerTick", ply)
-- end
```
Reason: One hook.Run call 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 to avoid repeating the player lookup and method call three times.


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

for i = 1, #items do
    draw.SimpleText(items[i].text, "DermaDefault", items[i].x, items[i].y, WHITE)
end
```
Reason: Create the color once outside the paint loop to avoid 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 global and table lookups inside the hot loop.


```lua
local localPlayer

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

hook.Add("Think", "UseCachedLocalPlayer", function()
    if IsValid(localPlayer) then
        local position = localPlayer:GetPos()
        -- Use localPlayer here instead of calling LocalPlayer() again.
    end
end)
```
Reason: A cached local reference avoids repeated global function lookup and LocalPlayer retrieval after the client entity is initialized.


```lua
local FACE_TO_FACE_DOT = -0.8

local function AreAimDirectionsFacingEachOther(playerA, playerB)
    return playerA:GetAimVector():Dot(playerB:GetAimVector()) <= FACE_TO_FACE_DOT
end
```
Reason: The dot product compares the already-normalized aim vectors directly; values near -1 mean opposite, face-to-face directions without the cost of math.acos.


```lua
SomeHelper(ply)
```
Reason: It is generally slightly faster because it avoids the implicit `self` method-call lookup and dispatch; use `:` only when method semantics or metatable-based organization matter.


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


```lua
for i = 1, #numbers do
    local number = numbers[i]
    -- use number
end
```
Reason: A numeric `for` loop avoids the iterator and function-call overhead of `pairs` and `ipairs`, making it typically fastest for large sequential arrays.


```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: A 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 i = 1, #cachedPlayers do
    playerIndex[cachedPlayers[i]] = i
end

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

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

hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", 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 i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Per-player tick work here.
    end
end)
```
Reason: This removes the per-tick player.GetAll allocation and uses O(1) join, removal, and indexed iteration over the cached array.


```lua
local playerData = {}

hook.Add("PlayerInitialSpawn", "InitFastPlayerData", function(ply)
    playerData[ply] = 0
end)

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

-- Hot read path:
local value = playerData[ply]
```
Reason: A direct Lua table lookup avoids the slower Player userdata/metatable field lookup, while disconnect cleanup prevents stale player references.


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

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


```lua
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Passing separate numeric channels avoids Color object creation and table-field access in the hot draw path.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64))
```
Reason: Local SQLite is typically lower latency because it avoids network round trips; use MySQL when shared multi-server access or external database tooling is required.


```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: Steam IDs are stable for a player's lifetime, so a weak-key cache replaces repeated engine calls with table lookups without retaining disconnected player entities.


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

-- Faster: collect pieces, then join them once.
local pieces = {}
for i = 1, 10000 do
    pieces[i] = tostring(i)
end
local result = table.concat(pieces, "\n")
```
Reason: table.concat avoids repeatedly allocating and copying the entire growing string.


```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 corner radius is zero.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(20, 20)
surface.DrawText("Single-line text")
```
Reason: surface.DrawText avoids the extra alignment, newline handling, and outline passes performed by draw.DrawText and draw.SimpleTextOutlined.


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


```lua
t = {}
```
Reason: Rebinding is generally faster because it allocates a new empty table instead of iterating through and deleting every entry in the existing table; use table.Empty(t) only when other references must observe the same table being cleared.


```lua
local values = { "admin", "moderator", "user" }

-- Slower: scans the whole list until it finds a match.
local exists = table.HasValue(values, "moderator")

-- Faster: store values as keys for direct lookup.
local valueSet = {
    admin = true,
    moderator = true,
    user = true,
}

exists = valueSet["moderator"] == true
```
Reason: A set-style key lookup is effectively O(1), while table.HasValue performs an O(n) linear scan of the list.


```lua
local playerData = {
    health = 100,
    armor = 50,
    alive = true,
}
```
Reason: Putting known fields in the table constructor is faster because Lua creates and initializes the table in one operation instead of performing separate field assignments.


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


```lua
local squared = x * x
```
Reason: Direct 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 each currently connected player 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 the engine's entity list directly instead of 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.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid verifies that ent exists and has not been removed before a method is called.


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


```lua
local ZERO_ANGLE = angle_zero
local ang = ZERO_ANGLE -- treat as read-only
```
Reason: Reusing Garry's Mod's cached zero Angle avoids the constructor call and allocation in the hot path.


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


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP networks `job` through its DarkRPVar API; `GetNWString("job")` reads a separate engine networked-string slot.


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


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


```lua
local nearbyEntities = ents.FindInSphere(player:GetPos(), 512)
```
Reason: `ents.FindInSphere` uses Garry's Mod's built-in spatial partition and is typically faster than scanning every entity in Lua.


```lua
local function FindPlayersInRadius(position, radius)
    local radiusSquared = radius * radius
    local nearby = {}
    local count = 0

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

    return nearby
end
```
Reason: Iterating only players avoids scanning unrelated entities, while DistToSqr avoids a square root and player.Iterator avoids creating a player-list table.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric for loops use specialized VM instructions and avoid the explicit increment required by while loops, so they are generally faster.


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

    -- Faster: dispatch the hook once, then process every player.
    hook.Run("CustomPlayerTick", players)

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

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


```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 frame’s health value once, avoiding two redundant Lua-to-engine method calls.


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

for i = 1, #items do
    surface.SetDrawColor(white)
    -- paint items[i]
end
```
Reason: Create the Color once outside the hot loop to avoid allocating a new color table on every iteration.


```lua
local sin = math.sin

for i = 1, count do
    values[i] = sin(i)
end
```
Reason: Localizing `math.sin` avoids a global-table lookup on every iteration.


```lua
local localPlayer

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

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

    local position = localPlayer:GetPos()
    local health = localPlayer:Health()
    -- Reuse localPlayer throughout hot code paths.
end)
```
Reason: Cache the player entity once after client entities initialize, then reuse the local upvalue instead of repeatedly calling the global LocalPlayer function.


```lua
local FACING_DOT = -0.8 -- -1 = directly opposite

local function AimDirectionsFaceEachOther(playerA, playerB)
    return playerA:GetAimVector():Dot(playerB:GetAimVector()) <= FACING_DOT
end
```
Reason: Aim vectors are normalized, so their dot product is the cosine directly; values near -1 mean opposing directions without the cost of math.acos.


```lua
SomeHelper(ply)
```
Reason: A direct helper call generally avoids the entity method/metatable lookup required by `ply:SomeHelper()`, especially when `SomeHelper` is local.


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


```lua
for i = 1, #numbers do
    local value = numbers[i]
    -- use value
end
```
Reason: Numeric `for` with direct indexing typically beats `ipairs` and `pairs` by avoiding iterator overhead; it requires a dense sequential table.


```lua
local function eligibleJobNames(jobs, maxSalary)
    local names = {}
    local count = 0

    for i = 1, #jobs do
        local job = jobs[i]
        if job.salary <= maxSalary and not job.admin then
            count = count + 1
            names[count] = job.name
        end
    end

    return names
end
```
Reason: One numeric loop performs both filter and map without fn callback dispatch, closures, or intermediate tables.


```lua
local cachedPlayers = {}
local playerIndices = {}

local function AddPlayer(ply)
    if playerIndices[ply] then return end

    local index = #cachedPlayers + 1
    cachedPlayers[index] = ply
    playerIndices[ply] = index
end

local function RemovePlayer(ply)
    local index = playerIndices[ply]
    if not index then return end

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

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

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

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

hook.Add("PlayerInitialSpawn", "PlayerCache_Add", AddPlayer)
hook.Add("PlayerDisconnected", "PlayerCache_Remove", RemovePlayer)

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: Join/leave hooks maintain the array, so Tick avoids player.GetAll(), ipairs(), and a fresh full-player traversal source every frame.


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

someFieldByPlayer[ply] = value
local value = someFieldByPlayer[ply]
```
Reason: A local table lookup avoids the Entity userdata/metatable lookup used by `ply.someField`, while weak keys prevent stale players from being retained.


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

for i = 1, #values do
    local value = values[i]
    -- Use value.
end
```
Reason: Sequential number-indexed arrays use the table’s array part and support fast numeric iteration, while string-keyed maps require hash traversal.


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


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


```lua
local steamIDCache = {}

hook.Add("PlayerAuthed", "CachePlayerSteamID", function(ply, steamID)
    steamIDCache[ply] = steamID
end)

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

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

    steamID = ply:SteamID()
    if steamID ~= "STEAM_ID_PENDING" then
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: A local table lookup avoids repeated engine-boundary calls and string work, while auth-time population and disconnect cleanup keep the cache correct.


```lua
-- Slow: allocates a new growing string on every iteration.
local result = ""
for i = 1, #pieces do
    result = result .. pieces[i]
end

-- Faster: collect pieces, then join once.
local buffer = {}
for i = 1, #pieces do
    buffer[i] = pieces[i]
end
local fastResult = table.concat(buffer)
```
Reason: table.concat avoids repeatedly copying the entire growing string, reducing allocations and near-quadratic copying.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: surface.DrawRect draws a plain rectangle directly and avoids draw.RoundedBox's rounded-box setup and Lua overhead.


```lua
local label = "Fast HUD text"

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(24, 24)
    surface.DrawText(label)
end)
```
Reason: Direct surface calls avoid draw.DrawText’s layout work, while SimpleTextOutlined draws the text multiple times to create its outline.


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


```lua
t = {}
```
Reason: Replacing the reference is generally faster than visiting and removing every entry with `table.Empty(t)`, provided no other code needs the original table cleared in place.


```lua
-- Slower: O(n) linear scan
local allowedList = { "prop_physics", "prop_dynamic", "prop_ragdoll" }
local existsSlow = table.HasValue(allowedList, className)

-- Faster: O(1) average lookup
local allowedSet = {
    prop_physics = true,
    prop_dynamic = true,
    prop_ragdoll = true,
}
local existsFast = allowedSet[className] == true
```
Reason: A keyed set avoids table.HasValue's linear scan by using an average O(1) hash lookup.


```lua
local t = {
    x = 1,
    y = 2,
    enabled = true,
}
```
Reason: Putting known fields in the constructor lets Lua create and populate the table directly, avoiding separate assignment operations.


```lua
local value = tbl[math.random(#tbl)]
```
Reason: Sequential tables support direct numeric indexing, avoiding table.Random's key traversal overhead.


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the slower exponentiation operator 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 temporary table returned by player.GetAll().


```lua
local ent = ents.FindByClass("prop_physics")
for _, entity in ipairs(ent) do
    -- Visit entity
end
```
Reason: Garry's Mod does not expose a public class-filtered entity iterator; `ents.FindByClass` is the supported API but builds a result table.


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid` returns true only for a non-nil, non-NULL entity that has not been removed, so calling entity methods inside the guard is safe.


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


CLI exited without a valid strict response.


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


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores job data as a DarkRP variable; this avoids depending on the legacy/general networked-string lookup.


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


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
```
Reason: `ents.FindInSphere` is a direct spatial-radius query and is commonly faster for nearby-entity checks than visibility/PVS-based selection.


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

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

    return playersNear
end
```
Reason: Iterating only `player.GetAll()` avoids the broader entity-sphere query and filters with squared distances, avoiding square-root work.


```lua
-- Faster: one hook dispatch per tick; listeners iterate the player list if needed.
hook.Run("MyTickPlayers", player.GetAll())

-- Slower: dispatches the hook once for every player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTickPlayer", ply)
end
```
Reason: The first pattern performs one hook lookup and dispatch per tick instead of one per player, reducing repeated hook-system overhead.


```lua
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)
```
Reason: Cache the per-frame health value so `LocalPlayer():Health()` runs once instead of three times.


```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 immutable color table avoids allocating a new Color object 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/global lookups in the hot loop.


```lua
SomeHelper(ply)
```
Reason: Passing `ply` explicitly avoids a metatable method lookup and implicit `self` argument handling, so it is generally faster for helpers you control.


```lua
MsgN("debug line")
```
Reason: MsgN is Garry's Mod’s native console-output function and avoids print’s extra Lua-side formatting overhead.


```lua
for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: A numeric `for` over a dense sequential table avoids the iterator-call overhead of `pairs` and `ipairs`; `pairs` is also unordered and may visit non-array keys.


```lua
-- Faster for a one-off pipeline: one direct loop, no fn closures/intermediate tables.
local function activePlayerNames(players)
    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

    return names
end

-- Instead of:
-- fn.map(fn.filter(players, function(p) return IsValid(p) and p:Alive() end),
--        function(p) return p:Nick() end)
local names = activePlayerNames(player.GetAll())
```
Reason: A single indexed loop avoids combinator callback dispatch, closure overhead, and the intermediate filtered table.


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

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

hook.Add("PlayerInitialSpawn", "RefreshCachedPlayersOnJoin", function()
    -- Run after the player has entered player.GetAll().
    timer.Simple(0, refreshCachedPlayers)
end)

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

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Per-tick player work here.
    end
end)
```
Reason: `player.GetAll()` allocates/builds the player list once per join or leave instead of on every tick, while numeric indexing avoids `ipairs` iterator overhead.


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

function Player:SetTempValue(value)
    playerData[self] = value
end

function Player:GetTempValue()
    return playerData[self]
end

-- Hot-path read:
local value = playerData[ply]
```
Reason: A plain side table avoids Player metatable field lookup and keeps temporary Lua-side state separate from the engine entity.


```lua
-- Faster: a sequential number-indexed array.
local values = { "alpha", "bravo", "charlie" }

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

-- Slower for fixed ordered iteration: string-keyed map.
local valuesByName = {
    first = "alpha",
    second = "bravo",
    third = "charlie",
}
```
Reason: Sequential integer keys use Lua's array part and support a tight indexed loop; string-keyed maps require hash-table lookup and unordered traversal.


```lua
-- Faster in a hot draw path: avoid constructing/passing a Color table.
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Separate numeric arguments avoid Color-object table access and argument unpacking overhead.


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


```lua
local steamIdCache = setmetatable({}, { __mode = "k" }) -- weak player keys

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)
```
Reason: It calls `ply:SteamID()` once per player and uses weak keys so disconnected player objects are not kept alive by the cache.


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

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

-- Fast: joins all pieces in one operation.
local fast = table.concat(pieces)
```
Reason: `table.concat` avoids repeatedly copying the growing string, so it performs far fewer allocations and copies.


```lua
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain rectangle directly, avoiding `draw.RoundedBox`’s rounding/setup overhead when the corner radius is zero.


```lua
-- Set these once (for example, during initialization).
surface.CreateFont("HudFast", {
    font = "Roboto",
    size = 24,
    weight = 500,
})

-- In HUDPaint: surface text helpers avoid draw.DrawText/SimpleTextOutlined overhead.
surface.SetFont("HudFast")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(24, 24)
surface.DrawText("Health: 100")
```
Reason: For a single unoutlined line, surface.SetFont/SetTextColor/SetTextPos/DrawText is the lower-overhead path; cache the font setup and avoid SimpleTextOutlined unless you need its outline.


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


```lua
-- Faster when you can replace the reference:
t = {}
```
Reason: `t = {}` allocates a new empty table, while `table.Empty(t)` iterates through and removes the existing entries; use `table.Empty` only when other code must retain the same table reference.


```lua
-- Slower: scans every element in an array-like list (O(n)).
local allowedList = { "admin", "moderator", "vip" }
if table.HasValue(allowedList, playerRole) then
    -- allowed
end

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

if allowedRoles[playerRole] then
    -- allowed
end
```
Reason: `table.HasValue` linearly scans a list, while a key-based set performs an average constant-time hash lookup.


```lua
-- Faster: build known fields directly in the constructor.
local playerState = {
    health = 100,
    armor = 50,
    alive = true,
}

-- Slower: allocate an empty table, then perform separate field assignments.
-- local playerState = {}
-- playerState.health = 100
-- playerState.armor = 50
-- playerState.alive = true
```
Reason: A table constructor initializes the known fields as part of table creation, avoiding the separate post-allocation assignments.


```lua
local value = items[math.random(#items)]
```
Reason: For a dense sequential table, indexing a random integer directly avoids table.Random's extra table-shape handling and function-call overhead.


```lua
local squared = x * x
```
Reason: Direct multiplication is the idiomatic, fastest form and avoids function-call overhead.


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


```lua
local entity = ents.Iterator()

while true do
    entity = entity()
    if not IsValid(entity) then break end

    if entity:GetClass() == "prop_physics" then
        -- Handle entity
    end
end
```
Reason: `ents.Iterator()` iterates entities lazily, avoiding allocation of a full entity 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` confirms the reference is a valid entity (not nil, NULL, or removed) 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 handler for an incoming net message by name.


```lua
local zeroAngle = angle_zero

-- Hot path: reuse the shared immutable zero angle.
entity:SetAngles(zeroAngle)

-- Slower: allocates a new Angle object every call.
-- entity:SetAngles(Angle())
```
Reason: `angle_zero` is Garry's Mod's shared zeroed `Angle`, avoiding per-call allocation and garbage-collection work.


```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; use a flat module-local value when the setting does not need dynamic mutation.


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

-- Avoid for DarkRP job data:
-- local jobName = ply:GetNWString("job")
```
Reason: DarkRP stores and synchronizes job data through its DarkRPVar system, so `getDarkRPVar("job")` is the supported accessor and stays aligned with DarkRP's internal contract.


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


```lua
for _, entity in ents.Iterator() do
    -- Process entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator for visiting every entity on supported Garry's Mod versions.


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
```
Reason: `ents.FindInSphere` is a fast built-in spatial query for entities within a fixed radius, without relying on PVS visibility behavior.


```lua
local nearby = player.GetAll()
local radiusSqr = radius * radius

for i = #nearby, 1, -1 do
    if nearby[i]:GetPos():DistToSqr(position) > radiusSqr then
        table.remove(nearby, i)
    end
end
```
Reason: `player.GetAll()` limits the scan to players, avoiding entity enumeration; squared-distance checks avoid the square root used by ordinary distance comparisons.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric `for` is generally faster in Garry's Mod Lua because its counter, limit, and increment are handled by the VM rather than through explicit Lua-level loop control.


```lua
-- Faster: one hook dispatch per tick, with the player list as an argument.
local players = player.GetAll()
hook.Run("MyTickPlayers", players)

-- Slower: repeats hook lookup/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 listener iteration for every player; listeners can iterate the provided player list once.


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

    draw.SimpleText("Health: " .. health, "DermaLarge", 20, 20)
    surface.DrawRect(20, 60, health * 2, 20)
    draw.SimpleTextOutlined(health, "DermaDefault", 20, 90, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, color_black)
end)
```
Reason: Cache the player health once per frame and reuse it, avoiding two redundant Lua-to-engine method calls.


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

for i = 1, count do
    surface.SetDrawColor(WHITE)
    -- paint item
end
```
Reason: Creating the color once avoids allocating a new Color object on every loop 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 table lookups inside the hot loop.


```lua
local cachedLocalPlayer

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

-- Hot-path usage:
if IsValid(cachedLocalPlayer) then
    local position = cachedLocalPlayer:GetPos()
end
```
Reason: Cache the player reference once per frame and reuse it in hot paths, while updating it after the client entity becomes available or changes.


```lua
local function RoughlyLookingAtEachOther(a, b, threshold)
    threshold = threshold or 0.7

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

    -- Dot is -1 when directions are opposite (facing one another), +1 when aligned.
    return aAim:Dot(bAim) <= -threshold
end
```
Reason: A dot product avoids the expensive `math.acos`; compare it directly against a cosine-derived threshold.


```lua
SomeHelper(ply)
```
Reason: Passing `ply` explicitly avoids a metatable method lookup and is generally faster for helpers you control.


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


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


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

    return names
end

local names = activePlayerNames(player.GetAll())
```
Reason: A single indexed loop avoids combinator callbacks and intermediate tables, reducing allocations and function-call overhead.


```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-tick player work here.
    end
end)
```
Reason: `player.GetAll()` allocates/builds a player list, so refreshing it only on join or leave avoids that work every tick while keeping the cache current.


```lua
-- Dense numeric keys avoid repeated string-key lookup and keep the hot path compact.
local IDX_SOME_FIELD = 1

local function SetSomeField(ply, value)
    local data = ply.__hotData
    if not data then
        data = {}
        ply.__hotData = data
    end
    data[IDX_SOME_FIELD] = value
end

local function GetSomeField(ply)
    return ply.__hotData[IDX_SOME_FIELD]
end
```
Reason: A per-player table with numeric indexes is typically faster to read than a string-named player field because numeric table access is cheaper and avoids repeated string-key hashing.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: A sequential number-indexed array has an optimized contiguous array part and avoids hash lookups required by string-keyed maps.


```lua
-- Hot path: avoid constructing/passing a Color table.
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numeric channels avoids Color-table allocation and table argument handling.


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


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

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

-- Hot path:
local steamID = SteamIDCached(ply)
```
Reason: SteamID is stable for a connected player, so this avoids repeated method calls while weak keys prevent the cache from retaining player objects.


```lua
local parts = {}

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

local result = table.concat(parts, "")
```
Reason: `table.concat` builds the final string once, avoiding the repeated allocations and copying caused by `result = result .. piece` in a loop.


```lua
surface.DrawRect(x, y, width, height)
```
Reason: It draws the rectangle directly and avoids draw.RoundedBox's extra Lua-side wrapper work when no rounding is needed.


```lua
-- Faster for a single line: avoid draw.DrawText / draw.SimpleTextOutlined overhead.
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText("Status: ready")
```
Reason: surface.SetFont + SetTextColor + SetTextPos + DrawText is the lower-level surface path and avoids the extra alignment, table, and outline work in draw.DrawText or draw.SimpleTextOutlined.


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


```lua
-- Faster when you can replace the table reference:
t = {}
```
Reason: `t = {}` avoids iterating over and clearing every existing entry; use `table.Empty(t)` only when other code must keep the same table object.


```lua
-- Slow: table.HasValue scans every element (O(n)).
local allowedList = { "admin", "moderator", "vip" }
if table.HasValue(allowedList, userGroup) then
    -- allowed
end

-- Fast: use keys as a set for average O(1) lookup.
local allowedGroups = {
    admin = true,
    moderator = true,
    vip = true,
}

if allowedGroups[userGroup] then
    -- allowed
end
```
Reason: Keyed-table lookups avoid the linear scan that table.HasValue performs on a list.


```lua
-- Faster: allocate and initialize in one table constructor.
local playerState = {
    health = 100,
    armor = 0,
    alive = true,
}

-- Slower:
-- local playerState = {}
-- playerState.health = 100
-- playerState.armor = 0
-- playerState.alive = true
```
Reason: The table constructor performs initialization as part of creation, avoiding separate field-assignment operations.


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


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


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


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Use ent here
    end
end
```
Reason: `ents.Iterator()` visits entities incrementally, avoiding allocation of a full entity table from `ents.GetAll()`.


```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 `MyAddon.Think` identifier.


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


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


```lua
local ZERO_ANGLE = angle_zero

-- Hot path: reuse the engine-provided shared zero angle.
local function applyNeutralRotation(ent)
    ent:SetAngles(ZERO_ANGLE)
end

-- Avoid in hot paths:
-- ent:SetAngles(Angle()) -- allocates a new Angle object each call
```
Reason: `angle_zero` is the shared engine-provided `(0, 0, 0)` Angle, so reusing it avoids per-call Angle allocation and construction overhead.


```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 because it avoids global and table indexing operations.


```lua
-- Preferred: DarkRP's job table is authoritative and avoids networked-string state.
local jobName = team.GetName(ply:Team())

-- Avoid for job identity:
-- local jobName = ply:GetNWString("job")
```
Reason: `team.GetName(ply:Team())` reads DarkRP's current team/job directly; the `"job"` networked string is not the authoritative job API.


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


```lua
for ent in ents.Iterator() do
    -- use ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator for visiting every entity when the order is not important.


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


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

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

    return nearby
end
```
Reason: This scans only the player list and compares squared distances, avoiding allocation and filtering of every entity found in the sphere.


```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, limit, and increment are handled by the VM without repeated Lua-level condition and increment work.


Answer must contain 0 through 1 candidate loops.

```lua
-- Faster: one hook dispatch, all players passed as data.
local playerGetAll = player.GetAll

hook.Add("Think", "NotifyCustomLogic", function()
    hook.Run("CustomPlayerTick", playerGetAll())
end)

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

-- Slower: repeats hook lookup and dispatch once per player.
hook.Add("Think", "NotifyCustomLogicPerPlayer", function()
    local players = playerGetAll()
    for i = 1, #players do
        hook.Run("CustomPlayerTick", players[i])
    end
end)
```
Reason: Dispatching one hook avoids repeating Garry's Mod hook-table lookup and callback traversal for every player; iterate the players inside one handler instead.


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

    draw.SimpleText(health, "DermaLarge", 20, 20)
    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 55)
    surface.DrawText(health)
end)
```
Reason: Cache the player health once per HUDPaint frame and reuse it, avoiding two repeated Lua-to-engine 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 table on every paint-loop 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 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 avoids repeated global-table lookups while still fetching the current local player when needed.


```lua
-- `a` and `b` are valid player entities.
-- Dot products avoid math.acos: with normalized aim vectors, dot = cos(theta).
local function AreRoughlyLookingAtEachOther(a, b)
    local aAim = a:GetAimVector()
    local bAim = b:GetAimVector()

    -- 0.7 is roughly within 45 degrees of directly facing each other.
    return aAim:Dot(-bAim) >= 0.7
end
```
Reason: Aim vectors are normalized, so their dot product directly measures directional alignment without the expensive inverse-cosine angle calculation.


```lua
SomeHelper(ply)
```
Reason: A controlled helper called directly avoids Garry's Mod entity metatable method lookup; localize `SomeHelper` for the fastest hot-path form.


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


```lua
for i = 1, #values do
    local value = values[i]
    -- use i and value
end
```
Reason: A numeric `for` over a sequential array avoids the iterator-function overhead of `pairs` and `ipairs`; `pairs` also makes no ordering guarantee.


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

    return names
end

local names = activePlayerNames(player.GetAll())
```
Reason: A numeric single-pass loop avoids fn combinator calls, closure overhead, and the intermediate filtered table.


```lua
local players = {}

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

hook.Add("Initialize", "CachePlayers", refreshPlayers)
hook.Add("PlayerInitialSpawn", "CachePlayers", refreshPlayers)
hook.Add("PlayerDisconnected", "CachePlayers", refreshPlayers)

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #players do
        local ply = players[i]
        -- per-player tick work
    end
end)
```
Reason: `player.GetAll()` allocates/builds the player list only on join/leave events, so the per-tick hook iterates the cached array without rebuilding it every tick.


```lua
local PlayerState = {}

-- Write once / update when needed
PlayerState[ply] = value

-- Hot-path read
local value = PlayerState[ply]

-- Cleanup when the player leaves
hook.Add("PlayerDisconnected", "ClearPlayerState", function(ply)
    PlayerState[ply] = nil
end)
```
Reason: A plain table indexed by the player avoids Garry's Mod player metatable field lookup, making repeated reads cheaper.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential numeric keys provide LuaJIT's efficient array layout and support a tight indexed loop, unlike string-keyed hash-map lookups.


```lua
-- Hot path: avoid allocating/passing a Color table.
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate channel numbers avoids Color-table handling on each draw call.


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


```lua
-- Cache by stable player identity. Refresh 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 == nil then
        steamID = ply:SteamID()
        steamIdByPlayer[ply] = steamID
    end
    return steamID
end

-- Hot path:
local steamID = GetCachedSteamID(ply)
```
Reason: Avoids repeated native method calls while retaining a safe cache miss path and releasing disconnected player references.


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

-- Fast: concatenate once after collecting all pieces.
local result = table.concat(pieces)

-- Slow: repeated concatenation repeatedly copies the growing string.
-- local result = ""
-- for i = 1, #pieces do
--     result = result .. pieces[i]
-- end
```
Reason: `table.concat` builds the final string in one native operation, avoiding repeated allocations and copies of an ever-growing string.


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


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.DrawText` is the leanest of these options for unoutlined single-line text; `draw.DrawText` and `draw.SimpleTextOutlined` add wrapper work, and outlining requires extra draw passes.


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


```lua
-- Faster when you can replace the reference:
t = {}
```
Reason: Rebinding creates a new empty table in constant time, while table.Empty(t) must iterate through and clear each existing entry; use table.Empty only when other code must keep the same table reference.


```lua
-- Slow: scans every element in the list (O(n))
if table.HasValue({ "admin", "moderator", "user" }, role) then
    -- found
end

-- Fast: use a lookup set (average O(1))
local allowedRoles = {
    admin = true,
    moderator = true,
    user = true,
}

if allowedRoles[role] then
    -- found
end
```
Reason: A keyed lookup avoids the linear scan that `table.HasValue` performs on a list.


```lua
-- Faster for a small table with known fields:
local playerData = {
    name = "Alyx",
    health = 100,
    alive = true,
}

-- Rather than:
-- local playerData = {}
-- playerData.name = "Alyx"
-- playerData.health = 100
-- playerData.alive = true
```
Reason: The table constructor creates and initializes the known fields in one expression, avoiding separate field-assignment statements.


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


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the extra function-call and exponentiation overhead of `x ^ 2` 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
        -- Use ent here.
    end
end
```
Reason: ents.Iterator() traverses entities directly, avoiding the table allocation from ents.GetAll().


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


```lua
if IsValid(ent) then
    ent:Remove()
end
```
Reason: `IsValid` returns false for `nil`, invalid entity handles, 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-side handler for incoming messages sent with `net.Start("MyAddon.Sync")`.


```lua
local ang = angle_zero -- treat as immutable; do not modify it
```
Reason: `angle_zero` reuses Garry's Mod's shared zero Angle and avoids allocating a new `Angle()` on each hot-path call.


```lua
local myaddonColor = Color(255, 255, 255)
local color = myaddonColor
```
Reason: A local variable avoids global-name and table-field lookups, so it is the fastest frequent-read option.


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

-- Avoid for DarkRP job names:
-- local jobName = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` reads DarkRP’s job state through its supported API; `GetNWString` depends on legacy networked-variable storage and is not the correct DarkRP contract.


```lua
if pos1:DistToSqr(pos2) <= 256 * 256 then
    -- Within 256 units
end
```
Reason: `DistToSqr` avoids the square-root calculation required for actual distance.


```lua
for _, ent in ents.Iterator() do
    -- Use ent
end
```
Reason: ents.Iterator() visits entities without allocating the table created by ents.GetAll().


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
```
Reason: `ents.FindInSphere` uses the engine's spatial partition for a cheap radius query around the player.


```lua
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
```
Reason: Iterating only players avoids collecting unrelated entities, and squared-distance checks avoid square roots.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric `for` loops are generally faster in Garry's Mod Lua because iteration control is handled by Lua’s specialized loop bytecode.


```lua
-- Faster: one hook dispatch, with the player list as one argument.
hook.Run("MyTickPlayers", player.GetAll())

-- Slower: one hook dispatch per player.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTickPlayer", ply)
end
```
Reason: One hook.Run call avoids repeating hook lookup and listener dispatch for every player.


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

draw.SimpleText(health, "HUD", 20, 20, color_white)
draw.SimpleText(health, "HUD", 20, 45, color_white)
draw.SimpleText(health, "HUD", 20, 70, color_white)
```
Reason: Reads the player's health once per HUDPaint frame and reuses the local value for all three draws.


```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 color avoids allocating a new Color object 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 lookups in the hot loop.


```lua
local localPlayer

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

-- Hot path: reuse the cached entity.
if IsValid(localPlayer) then
    local position = localPlayer:GetPos()
end
```
Reason: Cache the LocalPlayer entity once after client entities initialize, then reuse the local reference in hot paths.


```lua
local function RoughlyLookingAtEachOther(playerA, playerB)
    return IsValid(playerA)
        and IsValid(playerB)
        and playerA:GetAimVector():Dot(playerB:GetAimVector()) <= -0.7
end
```
Reason: The dot product directly measures opposing normalized aim vectors, avoiding the expensive `math.acos` angle conversion.


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


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


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


```lua
local function alivePlayerNames(players)
    local names, 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

    return names
end

local names = alivePlayerNames(player.GetAll())
```
Reason: One indexed loop fuses filtering and mapping, avoiding fn combinator dispatch and intermediate table allocation.


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

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

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

hook.Add("Tick", "UseCachedPlayers", function()
    for index = 1, #cachedPlayers do
        local ply = cachedPlayers[index]
        -- Per-player tick work here.
    end
end)
```
Reason: `player.GetAll()` runs once at load and the cache changes only on join/disconnect, avoiding a fresh table allocation and lookup every tick.


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

temporary[ply] = value
local value = temporary[ply]
```
Reason: A direct Lua table lookup avoids the Player entity's metamethod-backed field access; weak keys also release data when the player entity is collected.


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

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential numeric keys use Lua’s array part and fast indexed traversal; string-keyed maps require hash lookups and generic iteration.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Separate numeric arguments avoid Color object/table handling on the hot draw path.


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


```lua
local function CachedSteamID(ply)
    local steamID = ply.__cachedSteamID
    if steamID == nil then
        steamID = ply:SteamID()
        ply.__cachedSteamID = steamID
    end

    return steamID
end

-- Hot path:
local steamID = CachedSteamID(ply)
```
Reason: The SteamID is stable for a connected player, so subsequent calls use a cheap Lua field read instead of repeatedly invoking `ply:SteamID()`.


```lua
local parts = {}

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

local result = table.concat(parts, "\n")
```
Reason: `table.concat` builds the final string in one native operation, avoiding repeated allocation and copying of the growing string caused by `..` in a loop.


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


```lua
hook.Add("HUDPaint", "DrawStatus", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255)
    surface.SetTextPos(24, 24)
    surface.DrawText("Status: connected")
end)
```
Reason: `surface.DrawText` draws the whole line directly and avoids the extra alignment, shadow, outline, and per-character work in `draw.DrawText` and `draw.SimpleTextOutlined`.


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


```lua
-- Faster when no other code needs to retain a reference to the old table:
t = {}
```
Reason: Reassignment only creates and binds a new empty table; `table.Empty(t)` must iterate through the large existing table and remove its entries.


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

-- Faster: O(1) average-case hash lookup
local allowed = {
    admin = true,
    moderator = true,
    vip = true,
}

if allowed[role] then
    -- allowed
end
```
Reason: `table.HasValue` scans the list linearly (O(n)); a set keyed by the value uses an average O(1) table lookup.


```lua
-- Faster for small, known tables: initialize fields in the constructor.
local playerState = {
    health = 100,
    armor = 0,
    alive = true,
}

-- Slower: create an empty table, then perform separate field assignments.
local playerStateSlower = {}
playerStateSlower.health = 100
playerStateSlower.armor = 0
playerStateSlower.alive = true
```
Reason: A table constructor creates and initializes the known fields in one expression, avoiding separate assignment operations.


```lua
local value = items[math.random(#items)]
```
Reason: Direct indexed lookup avoids table.Random's extra work when the table is a dense 1..#items sequence.


```lua
local squared = x * x
```
Reason: Direct multiplication avoids function-call overhead and is the idiomatic fast form.


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


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Handle ent here.
    end
end
```
Reason: `ents.Iterator()` streams entities through the loop instead of creating a table containing every map entity.


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


```lua
if IsValid(ent) then
    ent:DoSomething()
end
```
Reason: `IsValid(ent)` returns false for nil, invalid, or removed entities, preventing method calls on an unsafe reference.


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


```lua
local ang = angle_zero:Copy() -- fresh, mutable Angle(0, 0, 0)
```
Reason: `angle_zero:Copy()` returns a fresh zeroed Angle while avoiding a new `Angle()` constructor call.


```lua
local myaddonColor = Color(255, 255, 255)
local color = myaddonColor
```
Reason: A local variable is faster to read than a nested table field because it avoids table lookups; avoid globals, which are slower than locals.


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

-- Avoid for DarkRP job data:
-- local jobName = ply:GetNWString("job")
```
Reason: DarkRP stores and synchronizes job data through its DarkRPVar system, so `getDarkRPVar("job")` is the supported accessor.


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


```lua
for _, ent in ents.Iterator() do
    -- Visit ent
end
```
Reason: `ents.Iterator()` visits all entities without allocating the table returned by `ents.GetAll()`.


```lua
local nearbyEntities = ents.FindInSphere(ply:GetPos(), 512)
```
Reason: `ents.FindInSphere` is an engine-backed spatial query and is commonly one of the faster general-purpose choices for entities near a player.


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

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

    return playersInRadius
end
```
Reason: `player.Iterator()` visits only players without allocating `player.GetAll()`’s table, and squared-distance checks avoid the square root used by `Distance`.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric `for` uses Lua’s specialized counting-loop primitive and is generally faster than a manual `while` loop in Garry’s Mod Lua.


```lua
-- Faster: one hook dispatch, all players as an argument.
local players = player.GetAll()
hook.Run("MyTickPlayers", players)

-- Slower: repeats hook lookup and dispatch once per player.
-- for _, ply in ipairs(players) do
--     hook.Run("MyTickPlayer", ply)
-- end
```
Reason: One hook.Run avoids repeating hook dispatch overhead for every player; listeners can loop the supplied player list once.


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

    draw.SimpleText(health, "DermaLarge", 20, 20, color_white)
    draw.SimpleText(health, "DermaDefault", 20, 50, color_white)
    draw.SimpleText(health, "DermaDefaultBold", 20, 80, color_white)
end)
```
Reason: Reads health once per frame and reuses the converted value across all three draw calls.


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

for i = 1, count do
    surface.SetDrawColor(WHITE)
    -- paint work
end
```
Reason: Creates the Color table once instead of allocating a new one on every iteration.


```lua
local sin = math.sin

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