```lua
local function GetNearbyEntities( player, radius )
    return ents.FindInSphere( player:GetPos(), radius )
end
```
Reason: FindInSphere is a fast built-in spatial query using the engine's optimized sphere check, commonly benchmarked as one of the quickest FindIn* methods for nearby entity retrieval.


```lua
-- Cache the LocalPlayer reference once per frame or when needed
local localPlayer = LocalPlayer()

-- Update the cache when necessary (e.g., on Think hook or when player changes)
hook.Add("Think", "UpdateLocalPlayerCache", function()
    localPlayer = LocalPlayer()
end)

-- Use localPlayer instead of calling LocalPlayer() repeatedly
if localPlayer and localPlayer:Alive() then
    -- Your code here
end
```

Reason: Caching LocalPlayer() in a local variable and updating it only when necessary (like on Think hook) avoids the overhead of repeated global function lookups, improving performance in frequently called code.


```lua
-- Preferred: ply:SomeHelper()
-- Method call syntax is generally faster in Garry's Mod Lua
ply:SomeHelper()
```

Reason: Method call syntax (ply:SomeHelper()) is generally faster than function call syntax (SomeHelper(ply)) in Garry's Mod Lua because it avoids the overhead of argument table creation and leverages optimized C++ method dispatch internally.


```lua
-- Micro-optimization: cache the function reference outside the hot loop
local sin = math.sin

-- Hot loop - uses cached reference instead of global lookup each iteration
for i = 1, 1000000 do
    local result = sin(i * 0.01)
    -- use result...
end
```
Reason: Caching `math.sin` in a local variable avoids repeated global table lookups on every iteration of the hot loop, reducing overhead significantly in Garry's Mod Lua.


```lua
local t = {1, 2, 3, 4, 5}
for i = 1, #t do
    local v = t[i]
end
```
Reason: Numeric for is fastest because it avoids iterator function overhead and uses direct index access with a cached length.


Final response exceeds fixture byte cap of 2048.

```lua
-- Fast check if two players are roughly looking at each other
-- Uses dot product of aim vectors instead of acos for angle calculation
-- Returns true if angle between aim directions is less than threshold (e.g., 45 degrees)

local function ArePlayersLookingAtEachOther(p1, p2, angleThreshold)
    if not IsValid(p1) or not IsValid(p2) then return false end
    if not p1:GetPos() or not p2:GetPos() then return false end

    -- Get aim vectors (forward directions)
    local aim1 = p1:GetForward()
    local aim2 = p2:GetForward()

    if not aim1 or not aim2 then return false end

    -- Calculate dot product of aim vectors
    -- Dot product = cos(angle), so we compare against cos(threshold)
    local dot = aim1:Dot(aim2)

    -- Pre-calculate threshold cosine for performance
    -- For 45 degrees: math.cos(math.rad(45)) ≈ 0.707
    -- For 60 degrees: math.cos(math.rad(60)) = 0.5
    -- For 30 degrees: math.cos(math.rad(30)) ≈ 0.866
    local cosThreshold = math.cos(math.rad(angleThreshold or 45))

    return dot >= cosThreshold
end

-- Alternative version that also checks if they're facing roughly the same direction
-- (useful for "mutual awareness" scenarios)
local function ArePlayersFacingEachOther(p1, p2, distanceThreshold, angleThreshold)
    if not IsValid(p1) or not IsValid(p2) then return false end

    local pos1 = p1:GetPos()
    local pos2 = p2:GetPos()

    if not pos1 or not pos2 then return false end

    -- Check distance first (early out)
    local dist = pos1:Distance(pos2)
    if dist > (distanceThreshold or 500) then return false end

    -- Direction from p1 to p2
    local dir1 = (pos2 - pos1):GetNormalized()
    -- Direction from p2 to p1
    local dir2 = (pos1 - pos2):GetNormalized()

    -- Get aim vectors
    local aim1 = p1:GetForward()
    local aim2 = p2:GetForward()

    if not aim1 or not aim2 then return false end

    -- Check if p1 is looking at p2 (aim1 should align with dir1)
    local dot1 = aim1:Dot(dir1)
    -- Check if p2 is looking at p1 (aim2 should align with dir2)
    local dot2 = aim2:Dot(dir2)

    local cosThreshold = math.cos(math.rad(angleThreshold or 45))

    return dot1 >= cosThreshold and dot2 >= cosThreshold
end

return {
    ArePlayersLookingAtEachOther = ArePlayersLookingAtEachOther,
    ArePlayersFacingEachOther = ArePlayersFacingEachOther
}
```

Reason: Uses dot product comparison against pre-computed cosine threshold instead of math.acos for angle calculation, avoiding expensive trigonometric operations while providing a fast approximate check for mutual player awareness.


```lua
-- Faster pipeline for DarkRP using inline loops instead of fn combinators
local function pipeline(iterable, ...)
    local filters = { ... }
    local result = {}

    for i = 1, #iterable do
        local item = iterable[i]
        local pass = true

        for j = 1, #filters do
            local filter = filters[j]
            if filter.type == "filter" then
                if not filter.func(item) then
                    pass = false
                    break
                end
            elseif filter.type == "map" then
                item = filter.func(item)
            end
        end

        if pass then
            table.insert(result, item)
        end
    end

    return result
end

-- Usage: filter players, then map to names
-- local names = pipeline(players,
--     {type = "filter", func = function(p) return p:Team() == TEAM_DOCTOR end},
--     {type = "map", func = function(p) return p:GetName() end}
-- )
```

Reason: Inline loop-based pipeline avoids fn library's function call overhead and intermediate table allocations, using direct iteration and in-place transformations for better performance in DarkRP's high-frequency hook contexts.


```lua
local playerList = {}
local playerListValid = false

local function RefreshPlayerList()
    playerList = player.GetAll()
    playerListValid = true
end

hook.Add("PlayerInitialSpawn", "CachePlayers_OnJoin", function()
    playerListValid = false
end)

hook.Add("PlayerDisconnected", "CachePlayers_OnLeave", function()
    playerListValid = false
end)

hook.Add("Think", "CachePlayers_Think", function()
    if not playerListValid then
        RefreshPlayerList()
    end
    -- Use playerList here instead of player.GetAll()
    for _, ply in ipairs(playerList) do
        -- Your think logic here
    end
end)
```

Reason: Caches the player list and only refreshes it when players join or leave, avoiding the expensive player.GetAll() call every tick.


```lua
local chat = chat
local chat.AddText = chat.AddText

local function DebugFast(...)
    chat.AddText(Color(255, 255, 0), "[DEBUG] ", Color(255, 100, 100), ...)
end
```
Reason: Using chat.AddText is faster than print in hot paths because it avoids the overhead of the print function and string formatting, directly outputting to the chat console.


```lua
-- Fast per-player data storage using a table indexed by player object
local PlayerData = {}

-- Initialize data for a player when they join
hook.Add("PlayerInitialSpawn", "InitPlayerData", function(ply)
    PlayerData[ply] = {
        someField = nil,
        anotherField = 0,
        -- add more fields as needed
    }
end)

-- Clean up when player leaves
hook.Add("PlayerDisconnected", "CleanupPlayerData", function(ply)
    PlayerData[ply] = nil
end)

-- Example usage:
-- Set a value
PlayerData[ply].someField = value

-- Read a value (faster than ply.someField)
local val = PlayerData[ply].someField
```

Reason: Using a separate table indexed by player object avoids metatable lookups and direct field access on the player entity, which is significantly faster for frequent reads in Garry's Mod Lua.


Answer must contain 0 through 1 candidate loops.

```lua
-- Sequential number-indexed array (faster for iteration)
local items = { "apple", "banana", "cherry" }

for i = 1, #items do
    local item = items[i]
    -- process item
end

-- Generic for loop over array (also fast)
for _, item in ipairs(items) do
    -- process item
end
```

Reason: Sequential number-indexed arrays use numeric keys which Lua can iterate more efficiently than string-keyed maps due to optimized numeric loop handling and the use of `ipairs` which leverages the `__ipairsmeta` metamethod for direct array traversal.


```lua
local query = "SELECT * FROM players WHERE steamid = ?"
local result = sql.Query(query)
```

Reason: Local SQLite is typically lower latency for reads/writes in a single Garry's Mod server since it avoids network overhead and is optimized for local disk access, making it faster than remote MySQL for this use case.


```lua
-- Cached SteamID lookup for hot paths
local steamIDCache = {}

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

-- Optional: hook to clear cache when player leaves
hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIDCache[ply] = nil
end)
```
Reason: Caching SteamID avoids repeated string allocations and function calls in hot paths, with cleanup on player disconnect.


Answer must contain 0 through 0 candidate loops.

```lua
-- Faster: table.concat for building large strings
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "some data " .. i
end
local result = table.concat(parts)
```

Reason: table.concat is O(n) while repeated .. concatenation is O(n²) due to creating new strings each time.


```lua
local draw_rounded = draw.RoundedBox
local draw_no_rounded = surface.DrawRect

-- Faster alternative to draw.RoundedBox(0, x, y, w, h, color)
-- This draws a plain rectangle without any rounding calculations
local function FastBox(x, y, w, h, color)
    if not color or not istable(color) then return end
    render.SetColor(color)
    draw_no_rounded(x, y, w, h)
end

-- Usage: FastBox(x, y, width, height, Color(255, 0, 0, 255))
-- This is faster because it skips all corner radius calculations
-- and directly calls the underlying surface drawing function
```

Reason: Using surface.DrawRect directly is faster than draw.RoundedBox(0, ...) because it bypasses the corner radius calculations and uses the lower-level rendering function.


```lua
-- Faster text drawing in Garry's Mod client Lua
-- Using draw.SimpleText is generally faster than surface.* text helpers
-- and more efficient than draw.DrawText with outlined fonts

local function DrawTextFast(text, font, x, y, color, xalign, yalign)
    -- Pre-cache font to avoid repeated lookups
    surface.SetFont(font)
    local w, h = surface.GetTextSize(text)

    -- Calculate alignment offsets
    local offsetX = xalign == TEXT_ALIGN_CENTER and -w * 0.5 or (xalign == TEXT_ALIGN_RIGHT and -w or 0)
    local offsetY = yalign == TEXT_ALIGN_CENTER and -h * 0.5 or (yalign == TEXT_ALIGN_BOTTOM and -h or 0)

    -- Use draw.SimpleText for better performance than DrawText
    draw.SimpleText(text, font, x + offsetX, y + offsetY, color)
end

-- Example usage - call this in a hook like HUDPaint
hook.Add("HUDPaint", "FastTextDraw", function()
    DrawTextFast("Hello World", "DermaDefault", 400, 300, Color(255, 255, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```
Reason: draw.SimpleText is faster than draw.DrawText because it avoids the overhead of the outlined text rendering path, and it's more efficient than surface.SetTextPos/text drawing methods since it handles the entire draw operation in a single call without requiring multiple surface.* state changes.


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


```lua
-- Faster approach: table.Empty(t)
local t = {}
for i = 1, 1000000 do t[i] = i end
table.Empty(t)  -- Clears in-place, avoids new table allocation

-- Slower approach: t = {}
-- t = {} only reassigns the local variable, original table still exists in memory
-- and may be slower if other references exist
```
Reason: table.Empty(t) clears the table in-place without creating a new table, avoiding memory allocation overhead and potential issues with other references to the same table.


```lua
-- Method 1: Assign fields after creation
local t1 = {}
t1.a = 1
t1.b = 2
t1.c = 3

-- Method 2: Table constructor (faster)
local t2 = { a = 1, b = 2, c = 3 }
```

Reason: The table constructor is faster because it creates and populates the table in a single operation, avoiding multiple assignment statements.


```lua
-- Faster random element from a sequential table
local function fastRandom(t)
    return t[math.random(#t)]
end
```
Reason: Direct index access with math.random is faster than table.Random because it avoids the function call overhead and uses the table's length directly for sequential tables.


```lua
local x2 = x * x
```
Reason: Direct multiplication is faster than using pow() or other function calls in tight loops.


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

```lua
for _, player in ipairs(player.GetAll()) do
    -- do something with player
end
```
Reason: Using ipairs with player.GetAll() is the modern Garry's Mod convention for iterating over connected players, as it provides cleaner syntax and better performance than pairs for ordered iteration.


```lua
local set = { a = true, b = true, c = true }
local exists = set[value] ~= nil
```
Reason: Using a table as a dictionary with keys provides O(1) lookup, while table.HasValue iterates linearly with O(n) complexity.


```lua
hook.Add( "Think", "MyAddon.Think", function() end )
```
Reason: Uses hook.Add to register an empty callback on the Think hook with the unique identifier MyAddon.Think.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- visit each prop_physics entity
end
```
Reason: ents.FindByClass directly returns only matching entities, avoiding construction of a table of every map entity.


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


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid checks that ent is a non-NULL, not-removed entity, preventing errors from invalid references.


```lua
local color = myaddon.config.color
local read = color
```
Reason: Local variable access avoids repeated nested table lookups, making frequent reads fastest.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: getDarkRPVar is DarkRP's intended synchronized variable accessor, avoiding fragile raw network string reads.


```lua
if (a:DistanceSqr(b) < threshold * threshold) then
    -- within threshold
end
```
Reason: DistanceSqr avoids sqrt, giving faster threshold checks via squared comparison.


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSq = radius * radius
    local result = {}
    for _, ply in ipairs(player.GetAll()) do
        if IsValid(ply) and ply:GetPos():DistToSqr(pos) <= radiusSq then
            result[#result + 1] = ply
        end
    end
    return result
end
```
Reason: player.GetAll() only loops players and DistToSqr avoids sqrt, making it faster than ents.FindInSphere which scans all entities.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 128)
```
Reason: ents.FindInSphere is a native spatial-partition query that benchmarks faster than FindInBox and avoids PVS overhead.


```lua
local allEntities = ents.GetAll()
for i = 1, #allEntities do
    local ent = allEntities[i]
    -- visit ent
end
```
Reason: Caching ents.GetAll() and using a numeric loop is the efficient iteration pattern recommended by the GMod wiki.


```lua
for i = 1, n do
end
```
Reason: Numeric for loops are generally faster in Lua because the VM optimizes bounds evaluation and iteration.


```lua
local ang = Angle()
for i = 1, 1e6 do
    ang:Zero()
    -- use ang as a zeroed angle without allocating a new Angle()
end
```
Reason: Reusing a single Angle and resetting it with :Zero() avoids per-iteration allocation and GC overhead compared to constructing a new Angle() each time.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local y = sin(i)
end
```
Reason: Localizing math.sin into a local variable avoids repeated table lookups in the hot loop.


```lua
local hp = LocalPlayer():Health()
draw.SimpleText(hp, "Default", 10, 10, color_white)
draw.RoundedBox(4, 10, 30, 100, 20, Color(hp, 0, 0))
surface.DrawRect(10, 60, hp, 10)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids three separate function calls per frame, improving performance.


```lua
hook.Add("Tick", "FastNotify", function()
    hook.Run("CustomPlayerLogic", player.GetAll())
end)
```
Reason: Calling hook.Run once with the player table avoids repeated hook lookup and call overhead per player, making it faster than looping and calling per player.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "FastPaint", function()
    surface.SetDrawColor(white)
end)
```
Reason: Caching the Color object outside the loop avoids per-iteration table allocation and reduces garbage collection overhead.


```lua
MsgN("debug line")
```
Reason: MsgN writes directly to the console, avoiding print's vararg handling and tostring concatenation overhead.


```lua
SomeHelper(ply)
```
Reason: Direct call avoids table/metatable lookup overhead, making it generally faster than colon syntax.


```lua
local function playersFaceEachOther(a, b, thr)
    thr = thr or 0.5
    local dirAtoB = (b:GetPos() - a:GetPos()):GetNormalized()
    local dirBtoA = (a:GetPos() - b:GetPos()):GetNormalized()
    return a:GetAimVector():Dot(dirAtoB) > thr and b:GetAimVector():Dot(dirBtoA) > thr
end
```
Reason: Uses dot products of aim vectors with inter-player directions, comparing cosine thresholds directly to avoid math.acos.


```lua
local ply = LocalPlayer()

local function LocalPly()
    if not IsValid(ply) then
        ply = LocalPlayer()
    end
    return ply
end

hook.Add("Think", "example", function()
    local lp = LocalPly()
    if lp then
        -- use lp instead of LocalPlayer()
    end
end)
```
Reason: Caching the local player entity in a variable and only refreshing when invalid avoids repeated global function lookups, improving performance.


```lua
for i = 1, #t do
    local v = t[i]
end
```
Reason: numeric for is fastest as it avoids iterator function overhead and hash lookups used by pairs/ipairs.


```lua
local function fastFilterMap(list, pred, map)
    local out = {}
    local j = 0
    for i = 1, #list do
        local v = list[i]
        if pred(v) then
            j = j + 1
            out[j] = map(v)
        end
    end
    return out
end

-- Example: filter valid admins and map to nick
local result = fastFilterMap(player.GetAll(),
    function(p) return IsValid(p) and p:IsAdmin() end,
    function(p) return p:Nick() end)
```
Reason: Single-pass loop with direct calls avoids fn's multiple passes, closure overhead, and intermediate table allocations.


```lua
local fast = { "a", "b", "c" }
for i = 1, #fast do
    local v = fast[i]
end
```
Reason: Sequential integer-indexed arrays iterate faster than string-keyed maps because they avoid hash lookups and allow predictable numeric traversal.


```lua
local PlayerData = {}

-- Write:
PlayerData[ply:EntIndex()] = { someField = value }

-- Read (fast):
local val = PlayerData[ply:EntIndex()].someField
```
Reason: Integer-keyed plain Lua table lookups bypass entity __index metamethods, reducing per-read overhead.


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

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

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

hook.Add("Tick", "TickWithCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- per-tick logic here
        end
    end
end)
```
Reason: Reassigning the cached player table only on join/leave hooks avoids calling player.GetAll() every tick, reducing overhead.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate numbers avoids per-frame Color object allocation, reducing GC pressure and call overhead in hot draw loops.


```lua
local data = sql.Query("SELECT score FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: Local SQLite avoids network round-trips, giving lower read/write latency than remote MySQL for a single server.


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

local function GetCachedSteamID(ply)
    local id = steamIDCache[ply]
    if id then return id end
    id = ply:SteamID()
    steamIDCache[ply] = id
    return id
end
```
Reason: Weak-keyed cache avoids repeated native SteamID calls and prevents leaks when players disconnect.


```lua
hook.Add("HUDPaint", "FastSingleLine", function()
    surface.SetFont("Default")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(16, 16)
    surface.DrawText("FPS: " .. math.floor(1 / RealFrameTime()))
end)
```
Reason: Direct surface.* calls avoid the multi-line parsing and outline rendering overhead present in draw.DrawText and draw.SimpleTextOutlined, making single-line per-frame drawing faster.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Bypasses draw.RoundedBox's border-size checks and color-table handling by calling surface drawing functions directly.


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


```lua
t = {}
```
Reason: t = {} avoids iterating over all elements and just reassigns the reference, making it faster than table.Empty for large sequential tables.


```lua
local t = { a = 1, b = 2, c = 3 }
```
Reason: Using the table constructor initializes fields in one step, avoiding separate assignments and making it faster.


```lua
local list = { "a", "b", "c" }
local set = {}
for _, v in ipairs(list) do
    set[v] = true
end

if set["b"] then
    print("value exists")
end
```
Reason: Hash-set lookup is O(1) versus O(n) linear scan of table.HasValue.


```lua
for i = 1, n do
    local sq = x * x
end
```
Reason: Direct multiplication x * x avoids ^/math.pow overhead and locals speed up tight loops.


```lua
local function randomSeq(t)
    return t[math.random(#t)]
end
```
Reason: Uses # length operator and direct indexing instead of table.Count/pairs iteration, making it O(1) for sequential tables.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- visit each prop_physics entity
    print(ent:EntIndex())
end
```
Reason: ents.FindByClass returns only prop_physics entities, so no table of all map entities is built first.


```lua
hook.Add( "Think", "MyAddon.Think", function()

end )
```
Reason: Uses hook.Add to register an empty callback on the Think hook with the identifier MyAddon.Think.


Keeps pairs() rather than Iterator or a cached numeric for-loop.

```lua
for _, ply in pairs(player.GetAll()) do
end
```
Reason: Iterates the table of connected players returned by player.GetAll().


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: Uses net.Receive to register a callback that runs when the MyAddon.Sync net message is received.


OpenRouter message content was empty or missing.


```lua
if IsValid(ent) then
    -- safe to use ent
end
```
Reason: IsValid checks if ent is a valid non-NULL entity, preventing errors from using removed or invalid references.


```lua
if (vecA:DistToSqr(vecB) < threshold * threshold) then /* within distance */ end
```
Reason: DistToSqr compares squared distance, avoiding costly sqrt for threshold checks.


```lua
local color = myaddon.config.color
local current = color
```
Reason: Local variable reads avoid nested table lookups, making them faster than nested tables or globals.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: getDarkRPVar is the proper DarkRP API for retrieving the job, avoiding direct NWString usage.


```lua
local function GetPlayersInRadius(pos, radius)
    local found = {}
    local r2 = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if IsValid(ply) and ply:GetPos():DistToSqr(pos) <= r2 then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: Iterating only over player.GetAll() with squared distance checks avoids the overhead of enumerating all entities in the sphere.


```lua
local ply = Entity(1)
local nearby = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: ents.FindInSphere is a commonly benchmarked cheaper radius query than FindInPVS for nearby entity checks.


```lua
local cachedAng = Angle()
local function getZeroAng()
    cachedAng:Zero()
    return cachedAng
end
```
Reason: Reusing one Angle and resetting it with :Zero() avoids repeated C-side allocations and GC pressure compared to calling Angle() every time.


```lua
local all = ents.GetAll()
for i = 1, #all do
    local ent = all[i]
end
```
Reason: Caching ents.GetAll() and using a numeric for loop is the wiki-recommended efficient way to iterate all entities.


```lua
for i = 1, n do
end
```
Reason: Numeric for loops are generally faster in Lua as the limit and step are evaluated once and the VM optimizes the iteration compared to while loops.


```lua
hook.Add("Tick", "FastNotify", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)
```
Reason: Single hook.Run with all players avoids repeated hook lookup and call overhead per player.


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

hook.Add("HUDPaint", "MyHUD", function()
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Caching the Color object outside the paint loop avoids repeated table allocation each iteration.


```lua
hook.Add("HUDPaint", "FastHealthDraw", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText(hp, "Default", 10, 10)
    draw.SimpleText(hp, "Default", 10, 30)
    draw.SimpleText(hp, "Default", 10, 50)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids three redundant function calls per frame.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local v = sin(i)
end
```
Reason: Localizing math.sin avoids repeated table indexing on the math global each loop iteration.


```lua
local function roughlyLookingEachOther(p1, p2)
    local to2 = (p2:GetPos() - p1:GetPos()):GetNormalized()
    local to1 = -to2
    local thr = 0.5 -- ~60 deg cone, compare dot directly instead of acos
    return p1:GetAimVector():Dot(to2) > thr and p2:GetAimVector():Dot(to1) > thr
end
```
Reason: Dot product compares aim vectors to direction-between vectors against a cosine threshold, avoiding costly math.acos.


```lua
MsgN("debug line")
```
Reason: MsgN is a C-bound console output that bypasses print's Lua-side argument processing and string concatenation, reducing overhead in hot paths.


```lua
SomeHelper(ply)
```
Reason: Direct global/upvalue call avoids colon's implicit self and metatable method lookup, making it marginally faster.


```lua
local ply = LocalPlayer()

hook.Add("PlayerSpawn", "UpdateCachedLocalPlayer", function(p)
    if p == LocalPlayer() then
        ply = p
    end
end)

-- Use ply instead of LocalPlayer() in performance-critical code
if IsValid(ply) then
    ply:SetHealth(100)
end
```
Reason: Caching the local player in a local variable and updating it on spawn avoids repeated LocalPlayer() function call overhead.


```lua
for i = 1, #arr do
    local v = arr[i]
end
```
Reason: Numeric for is fastest due to direct index access and no iterator overhead.


```lua
local seq = { "a", "b", "c" }
for i = 1, #seq do
    local v = seq[i]
end
```
Reason: Sequential integer-indexed arrays iterate faster via numeric for/# length than string-keyed maps due to avoided hash lookups and pairs overhead.


```lua
local function filterMap(list, pred, trans)
    local out = {}
    local idx = 0
    for i = 1, #list do
        local v = list[i]
        if pred(v) then
            idx = idx + 1
            out[idx] = trans(v)
        end
    end
    return out
end

local data = {1, 2, 3, 4, 5, 6, 7, 8}
local result = filterMap(data,
    function(x) return x % 2 == 0 end,
    function(x) return x * x end
)
```
Reason: Single-pass loop with preallocated output table avoids intermediate allocations and multiple iterations inherent to DarkRP's fn combinator chaining.


```lua
local CachedPlayers = {}

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

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

hook.Add("Tick", "ProcessCachedPlayers", function()
    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        if IsValid(ply) then
            -- per-tick logic using ply
        end
    end
end)
```
Reason: Maintains a cached player table updated only on join/leave hooks, eliminating per-tick player.GetAll() calls.


```lua
local playerData = {}

local function SetPlayerData(ply, key, val)
    local idx = ply:EntIndex()
    local t = playerData[idx] or {}
    t[key] = val
    playerData[idx] = t
end

local function GetPlayerData(ply, key)
    local t = playerData[ply:EntIndex()]
    return t and t[key]
end
```
Reason: Integer-indexed local table lookups avoid entity metatable __index overhead, making reads faster than ply.someField.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate numbers avoids allocating a Color object each call, reducing GC pressure and call overhead in hot draw paths.


```lua
local res = sql.Query("SELECT score FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: Local SQLite avoids network round-trips, offering lower latency than remote MySQL for a single server.


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

local function GetCachedSteamID(ply)
    local id = steamIDCache[ply]
    if not id then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```
Reason: Caches SteamID per player using a weak-keyed table to avoid repeated native calls while preventing memory leaks.


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


```lua
hook.Add("HUDPaint", "FastNonRoundedRects", function()
    surface.SetDrawColor(255, 100, 0, 255)
    for i = 1, 150 do
        surface.DrawRect(i * 6, 100, 5, 30) -- directly draws filled rect, no rounding logic
    end
end)
```
Reason: surface.DrawRect is the lower-level primitive that avoids draw.RoundedBox's radius/corner branching, making it slightly faster for non-rounded rectangles.


```lua
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("Default")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Single line")
end)
```
Reason: surface.DrawText avoids the multi-line parsing and outline rendering overhead of draw.DrawText/SimpleTextOutlined, making it faster for single-line per-frame text.


```lua
t = {}
```
Reason: Reassigning to a new empty table avoids an O(n) iteration to nil out entries, making it generally faster than table.Empty for large sequential tables.


```lua
local t = { a = 1, b = 2 }
```
Reason: Using the table constructor initializes fields in one step, avoiding separate assignments and being faster than assigning after {}.


```lua
local list = { "a", "b", "c" }
local set = {}
for _, v in ipairs(list) do set[v] = true end

local exists = set["b"] ~= nil -- O(1) lookup, faster than table.HasValue(list, "b")
```
Reason: Key-based lookup is O(1) whereas table.HasValue performs an O(n) linear scan.


```lua
local function seqRandom(t)
    return t[math.random(#t)]
end
```
Reason: Direct indexing with the length operator avoids pairs iteration and counting overhead used by table.Random, making it faster for sequential arrays.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- do something with ent
end
```
Reason: ents.FindByClass returns only entities of the given class, avoiding iterating all map entities first.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```
Reason: Uses hook.Add to register an empty callback on the Think hook with the identifier MyAddon.Think.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: IsValid checks that ent is a non-null entity that hasn't been removed or invalidated.


```lua
for _, ply in pairs(player.GetAll()) do
end
```
Reason: Uses player.GetAll() to obtain all connected players and iterates with pairs.


```lua
for i = 1, n do
    local sq = x * x
end
```
Reason: Direct multiplication x * x is faster than x^2 or math.pow in Lua tight loops.


```lua
util.AddNetworkString("MyAddon.Sync")
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming net message here
end)
```
Reason: util.AddNetworkString registers the net message name and net.Receive attaches the handler for incoming messages with that name.


```lua
local ZeroAngle = Angle(0, 0, 0)
-- reuse ZeroAngle by copying when mutation is needed:
local a = ZeroAngle
```
Reason: Reusing a preallocated zero Angle avoids repeated constructor overhead in hot paths.


```lua
local myaddon_color = Color(255, 0, 0)
local read = myaddon_color
```
Reason: A flat local variable avoids table lookups, making frequent reads faster than nested table access.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores the job name in its own synchronized variable, so getDarkRPVar("job") is the supported and reliable API instead of the generic NWString.


```lua
if (vecA:DistToSqr(vecB) <= threshold * threshold) then
    -- within threshold
end
```

Reason: DistToSqr avoids the square root and is the preferred method for threshold distance checks.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- do something with ent
end
```

Reason: ents.GetAll() with ipairs is the efficient wiki-recommended way to iterate all entities in Garry's Mod.


```lua
local ply = Entity(1)
local radius = 256
local ents = ents.FindInSphere(ply:GetPos(), radius)
```
Reason: ents.FindInSphere is a commonly benchmarked fast built-in spatial query alternative to FindInPVS for nearby entities.


```lua
local found = {}
local pos = Vector(0,0,0)
local radius = 512
local radiusSq = radius * radius
for _, ply in ipairs(player.GetAll()) do
    if ply:GetPos():DistToSqr(pos) <= radiusSq then
        found[#found + 1] = ply
    end
end
```
Reason: Iterating player.GetAll() and using DistToSqr avoids entity-type filtering and square-root math, making it faster than ents.FindInSphere plus player checks.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: In Lua, numeric for loops are generally faster than while loops because the loop counter and limit are handled internally by the VM with less overhead.


```lua
-- Faster: call hook.Run once with the whole player table
hook.Run("TickAllPlayers", player.GetAll())

-- Slower: loop and call hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("TickPlayer", ply)
end
```
Reason: A single hook.Run with all players avoids repeated hook lookup and call overhead per player.


```lua
hook.Add("HUDPaint", "FastHealthDraw", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText("HP: " .. hp, "Default", 10, 10)
    draw.SimpleText("Half: " .. (hp * 0.5), "Default", 10, 30)
    draw.SimpleText("Double: " .. (hp * 2), "Default", 10, 50)
end)
```
Reason: Caching LocalPlayer():Health() in a local avoids three separate function calls per frame.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "Example", function()
    surface.SetDrawColor(white)
    -- draw stuff
end)
```

Reason: Reusing a preallocated Color table avoids per-frame allocation and garbage collection overhead.


```lua
local sin = math.sin
-- use sin(x) instead of math.sin(x) in the hot loop
```

Reason: Localizing math.sin avoids repeated table lookups in the hot loop.


```lua
local ply = LocalPlayer()
hook.Add("PlayerSpawn", "UpdateLocalPly", function(p)
    if p == ply then ply = p end
end)
-- use 'ply' instead of calling LocalPlayer() repeatedly
```

Reason: Caching the LocalPlayer reference in a local variable avoids repeated global/engine lookups and only updates on respawn.


```lua
local function lookingAtEachOther(p1, p2)
    local d = p2:GetPos() - p1:GetPos()
    local f1 = p1:GetAimVector()
    local f2 = p2:GetAimVector()
    return f1:Dot(d) > 0 and f2:Dot(-d) > 0
end
```

Reason: Dot product with direction vectors is cheaper than acos and checks if aims point toward each other.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the metatable lookup and method dispatch overhead of colon calls, so for a helper you control a plain function call is generally faster.


```lua
debug.getregistry().Console and debug.getregistry().Console("debug message\n") or Msg("debug message\n")
```
Reason: Using Msg or a cached console reference avoids print's vararg and formatting overhead, making it faster for hot paths.


```lua
local t = {1,2,3,4,5}
for i=1,#t do
    local v = t[i]
end
```
Reason: Numeric for with #t is fastest because it avoids iterator function overhead of pairs/ipairs and directly indexes the array.


```lua
local players = player.GetAll()
local result = {}
for i = 1, #players do
    local p = players[i]
    if IsValid(p) and p:isDarkRPAdmin() then
        local name = p:Nick()
        if name and #name > 0 then
            result[#result + 1] = string.upper(name)
        end
    end
end
```
Reason: A single tight loop with early checks avoids fn's closure overhead and intermediate tables, making it faster than combinator chaining.


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

hook.Add("PlayerConnect", "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]
        -- do per-player work here
    end
end)
```

Reason: Caching player.GetAll() and only updating on join/leave hooks avoids rebuilding the table every tick, reducing overhead.


```lua
local plyData = setmetatable({}, {__index = function(t, k) return {} end})

-- write
plyData[ply] = plyData[ply] or {}
plyData[ply].someField = value

-- read (fast, no metatable lookup on ply)
local field = plyData[ply].someField
```
Reason: Using a local table keyed by player avoids per-entity metatable/field lookups on the Entity userdata, making frequent reads faster.


```lua
local arr = { "a", "b", "c", "d" }
for i = 1, #arr do
    local v = arr[i]
    -- do work with v
end
```

Reason: Sequential numeric arrays with ipairs-style or count-based loops avoid hash lookups and are faster than iterating string-keyed maps in Lua.


```lua
surface.SetDrawColor(255, 0, 0)
```
Reason: Passing separate numbers avoids Color object allocation and method overhead in hot draw loops.


```lua
local db = sql.Query("SELECT score FROM player_data WHERE steamid = " .. sql.SQLStr(ply:SteamID()))
```

Reason: Local SQLite avoids network round-trips so reads/writes have lower latency than remote MySQL for single-server use.


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

local function GetCachedSteamID(ply)
    local id = steamIDCache[ply]
    if not id then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```
Reason: Caches SteamID per player in a weak-keyed table to avoid repeated native calls while allowing GC of disconnected players.


```lua
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect skips the rounding math and path building that draw.RoundedBox(0,...) does, making it slightly faster for non-rounded rectangles.


```lua
hook.Add("HUDPaint", "FastText", function()
    draw.SimpleTextOutlined("Hello", "DermaDefault", 100, 100, Color(255,255,255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, Color(0,0,0))
end)
```
Reason: draw.SimpleTextOutlined batches text drawing internally and avoids per-call font/color state setup overhead compared to manual surface.* calls.


```lua
local len = #mytable
```

Reason: The length operator # is the idiomatic and efficient way to get the length of a sequential array-like table in Lua.


```lua
t = {}
```

Reason: Reassigning to a new empty table is faster than clearing all elements in-place because it avoids iterating over and nil-ing every existing index.


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


```lua
local set = { ["value1"] = true, ["value2"] = true }
if set["value1"] then
    -- exists
end
```
Reason: Using a hash table with boolean values allows O(1) lookups, unlike table.HasValue which does a slow O(n) linear scan.


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

Reason: Using the table constructor avoids extra key assignments and is faster since the table is built in one step.


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

Reason: Using math.random with the table length directly avoids table.Random's generic iteration and extra checks, making it faster for sequential tables.


```lua
local y = x * x
```

Reason: Multiplication is faster and simpler than math.pow(x,2) in tight loops.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- ply is the current connected player
end
```

Reason: Using ipairs with player.GetAll() cleanly iterates each connected player in order without needing the key.