OpenRouter message content was empty or missing.


Uses IsValid for entity/object validity.


Answer must contain 0 through 0 candidate loops.


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


Final response exceeds fixture byte cap of 2048.


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


OpenRouter error: Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (122/32) (code 502)


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


```lua
net.Receive("MyAddon.Sync", function(len)
    -- handle incoming data
end)
Reason: Registers a net.Receive handler for MyAddon.Sync to process incoming messages.
```


```lua
for i = 1, n do
    -- body
end
```
Reason: The numeric for loop is faster because it's implemented in C and avoids the per‑iteration overhead of manual condition checks and increments in a while loop.


```lua
-- Faster: call hook.Run once with all players
hook.Run("MyCustomLogic", player.GetAll())

-- Slower: loop per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomLogic", ply)
end
```
Reason: Calling hook.Run once with all players avoids repeated hook dispatch overhead, making it significantly faster than iterating and calling hook.Run per player.


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


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

hook.Add("HUDPaint", "FastWhitePaint", function()
    surface.SetDrawColor(white)
    surface.DrawRect(10, 10, 100, 50)
end)
```
Reason: Predefine the Color object once and reuse it each frame to avoid unnecessary object creation.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local v = sin(i)
    -- use v
end
```
Reason: Localizing math.sin eliminates repeated global table lookups, reducing overhead in hot loops.


```lua
-- Cache the LocalPlayer function to avoid repeated lookups
local GetLocalPlayer = LocalPlayer

-- Example usage in a hook
hook.Add("Think", "FastLocalPlayer", function()
    local ply = GetLocalPlayer()
    if IsValid(ply) then
        -- Use ply here
    end
end)
```
Reason: Storing a reference to the LocalPlayer function eliminates the global table lookup each call, making repeated accesses faster.


```lua
local function PlayersFaceEachOther(plyA, plyB, cosThreshold)
    cosThreshold = cosThreshold or 0.7 -- adjust for "roughly" (dot > 0.7 => angle < ~45°)
    local aimA = plyA:GetAimVector()
    local aimB = plyB:GetAimVector()
    local dirToB = (plyB:GetPos() - plyA:GetPos()):GetNormalized()
    local dirToA = (plyA:GetPos() - plyB:GetPos()):GetNormalized()
    return aimA:Dot(dirToB) > cosThreshold and aimB:Dot(dirToA) > cosThreshold
end
```
Reason: Uses dot products of aim vectors with the direction to the other player, avoiding costly acos calculations while providing a fast, approximate facing check.


```lua
SomeHelper(ply)
Reason: Direct function call avoids the table lookup involved in colon syntax, making it slightly faster.
```


```lua
MsgN("Debug: ", someVar)
```
Reason: MsgN outputs directly to the console with minimal overhead, avoiding the formatting cost of Lua's print function.


```lua
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: Numeric for loop avoids iterator overhead and is optimized by LuaJIT, making it the fastest for sequential arrays.


```lua
-- Fast filter/map without fn combinator overhead
local function fastFilter(list, pred)
    local out = {}
    local j = 0
    for i = 1, #list do
        local v = list[i]
        if pred(v) then
            j = j + 1
            out[j] = v
        end
    end
    return out
end

local function fastMap(list, func)
    local out = {}
    for i = 1, #list do
        out[i] = func(list[i])
    end
    return out
end

-- Example usage:
-- local players = player.GetAll()
-- local admins = fastFilter(players, function(p) return p:IsAdmin() end)
-- local adminNames = fastMap(admins, function(p) return p:Nick() end)
```
Reason: Plain Lua loops avoid the metaprogramming and temporary function overhead of DarkRP's fn combinator library, making filter/map pipelines faster.


```lua
-- Cached player table
local cachedPlayers = {}

-- Function to rebuild cache
local function rebuildPlayerCache()
    cachedPlayers = {}
    for _, ply in ipairs(player.GetAll()) do
        table.insert(cachedPlayers, ply)
    end
end

-- Hooks to keep cache up to date
hook.Add("PlayerInitialSpawn", "CachePlayersOnJoin", function(ply)
    table.insert(cachedPlayers, ply)
end)

hook.Add("PlayerDisconnect", "CachePlayersOnLeave", function(ply)
    for i, p in ipairs(cachedPlayers) do
        if p == ply then
            table.remove(cachedPlayers, i)
            break
        end
    end
end)

-- Initialize cache on server start
rebuildPlayerCache()

-- Example tick/think hook using cached table
hook.Add("Think", "FastPlayerThink", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- Replace with your per‑tick logic
            -- print(ply:Nick())
        end
    end
end)
```

Reason: Maintains a cached player list updated only on join/leave events, avoiding the costly ipairs(player.GetAll()) each tick.


Answer must contain 1 through 1 non-empty reason lines.

```lua
local PlayerData = setmetatable({}, {__mode = "k"}) -- weak keys to prevent memory leaks

-- Store temporary data
function SetTempData(ply, key, value)
    if not PlayerData[ply] then PlayerData[ply] = {} end
    PlayerData[ply][key] = value
end

-- Retrieve temporary data
function GetTempData(ply, key)
    return PlayerData[ply] and PlayerData[ply][key]
end
```

Reason: A weak-keyed table provides O(1) lookups without the value
end

-- Read temporary data (fast)
function GetTempData(ply, key)
    return PlayerData[ply] and PlayerData[ply][key]
end
```

Reason: A weak-keyed table gives O(1) access with less overhead than reading fields directly from the player entity.


```lua
local arr = {10, 20, 30, 40}
for i = 1, #arr do
    local v = arr[i]
end
```
Reason: Sequential number-indexed arrays store values in contiguous integer slots, enabling fast iteration with a numeric loop or ipairs without the hash‑table overhead of string‑keyed maps.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate r, g, b, a numbers avoids creating a temporary Color object each frame, reducing garbage collection overhead and improving performance in hot draw paths.


```lua
local result = sql.Query("SELECT player_data FROM players WHERE steamid = ?", ply:SteamID64())
```
Reason: Local SQLite eliminates network round‑trip overhead, giving lower latency for reads/writes on a single‑server setup.


```lua
local steamIDCache = setmetatable({}, { __mode = "k" }) -- weak keys to avoid memory leaks

local function GetSteamID(ply)
    if not IsValid(ply) then return "BOT" end
    local cached = steamIDCache[ply]
    if cached ~= nil then
        return cached
    end
    local id = ply:SteamID()
    steamIDCache[ply] = id
    return id
end
```
Reason: Caching each player's SteamID eliminates repeated costly calls, and a weak-key table lets the cache be garbage‑collected when players leave.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "chunk" .. i
end
local bigString = table.concat(pieces)
```
Reason: Using table.concat builds the string in linear time by avoiding repeated allocations and copies that occur with the .. operator.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect skips the extra function call and rounding logic of draw.RoundedBox, making it slightly faster for non‑rounded rectangles.


```lua
hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello, World!")
end)
```
Reason: surface.* helpers are lower-level and avoid the extra function call overhead of draw.DrawText/SimpleTextOutlined, making them faster per frame.


```lua
local length = #myTable
```
Reason: The # length operator returns the number of consecutive integer‑keyed elements from 1, which is the idiomatic way to get the size of a sequential array‑like table in Lua/Garry's Mod.


```lua
table.Empty(t)
```
Reason: table.Empty clears the table in place without allocating a new table, making it faster than reassigning t = {} which creates a new table and leaves the old one for garbage collection.


```lua
local lookup = { ["apple"] = true, ["banana"] = true, ["orange"] = true }
if lookup[someValue] then
    -- value exists in the set
end
```
Reason: Using a hash table (key‑value set) provides O(1) lookup, which is faster than table.HasValue’s O(n) linear scan over a list.


```lua
local t = {x = 10, y = 20, z = 30}
```
Reason: Table constructor creates the table with fields in one step, avoiding extra assignment operations.


```lua
local function fastRandom(seqTbl)
    return seqTbl[math.random(#seqTbl)]
end
```
Reason: Direct index access avoids the iteration overhead of table.Random for sequential tables.


OpenRouter error: Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (195/32) (code 502)


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
Reason: Iterates over all connected players using ipairs for ordered traversal.
```


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Replace this comment with your logic
    print(ent)
end
```
Reason: ents.FindByClass returns only entities of the specified class, avoiding the need to first build a table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body (can be empty)
end)
Reason: Registers a Think hook callback identified as MyAddon.Think.
```


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: IsValid returns true only for entities that still exist and haven't been removed, ensuring the reference is safe before calling methods on it.


OpenRouter error: Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (32/32) (code 502)


```lua
-- Pre‑allocate a zero angle once
local zeroAngle = Angle(0,0,0)

-- In hot path, reuse it by copying (no new allocation)
local ang = zeroAngle:Copy()
-- use ang as needed
```
Reason: Reusing a pre‑allocated zero Angle and copying it avoids allocating a new Angle object each call, reducing GC pressure in hot paths.


```lua
local myaddon_color = Color(255, 0, 0) -- flat local variable for fast access
local current = myaddon_color -- read
```
Reason: Local variable access is a single stack lookup, faster than global or nested table lookups which require hash table accesses.


```lua
-- Preferred way to get a player's job name in DarkRP
local jobName = ply:getDarkRPVar("job") -- returns the job string
-- Alternative using team index:
-- local jobName = team.GetName(ply:Team())
```
Reason: getDarkRPVar("job") is the replicated DarkRP variable for a player's job, providing a more reliable and up-to-date value than the generic NWString.


```lua
-- Check if two vectors are within a distance without computing sqrt
local function IsWithinThreshold(v1, v2, maxDist)
    return v1:DistToSqr(v2) <= maxDist * maxDist
end
```
Reason: DistToSqr gives the squared distance, avoiding the costly square‑root operation of Length.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- Your code here
end
Reason: Using ents.GetAll() with ipairs is the wiki-recommended efficient iterator for visiting all entities.
```


```lua
local ply = LocalPlayer() -- replace with your player reference
local radius = 256
local nearby = ents.FindInSphere(ply:GetPos(), radius)
for _, ent in ipairs(nearby) do
    -- process each nearby entity
    print(ent)
end
```
Reason: FindInSphere performs a simple distance check and is among the fastest built‑in spatial queries for finding entities near a point, outperforming FindInPVS for local proximity checks.


```lua
function GetPlayersInSphere(pos, radius)
    local r2 = radius * radius
    local players = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= r2 then
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: Iterating only over players avoids checking thousands of non‑player entities, making the search faster.


```lua
for i = 1, n do
    -- body
end
```
Reason: The numeric for loop is optimized in Lua and has less overhead than a while loop, making it generally faster for simple counting loops.


```lua
-- Inefficient: loop per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomTick", ply)
end

-- Efficient: pass all players at once
hook.Run("MyCustomTick", player.GetAll())
```
Reason: Calling hook.Run once with all players reduces the overhead of multiple hook invocations and avoids repeated loops, making it significantly faster per tick.


```lua
hook.Add("HUDPaint", "OptimizedHealthHUD", function()
    local health = LocalPlayer():Health()
    draw.SimpleText("Health: " .. health, "DermaDefault", 10, 10, Color(255,255,255))
    draw.SimpleText("Health: " .. health, "DermaDefault", 10, 30, Color(255,255,0))
    draw.SimpleText("Health: " .. health, "DermaDefault", 10, 50, Color(0,255,255))
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids repeated function calls per frame, reducing overhead.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "FastWhitePaint", function()
    surface.SetDrawColor(white)
    -- drawing code here
end)
```
Reason: Precomputing the Color object once avoids repeated allocation each paint iteration, improving performance.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local v = sin(i)
    -- use v
end
```
Reason: Localizing math.sin into a local variable eliminates the global table lookup each iteration.


```lua
-- Cache the local player to avoid repeated lookups
local ply = LocalPlayer()
-- Use `ply` wherever you need the player entity
```
Reason: Caching LocalPlayer() eliminates the repeated engine lookup, reducing overhead when the player entity is needed frequently.


```lua
function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.5
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local dir1to2 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local dir2to1 = (ply1:GetPos() - ply2:GetPos()):GetNormalized()
    return aim1:Dot(dir1to2) > threshold and aim2:Dot(dir2to1) > threshold
end
```
Reason: Dot products of aim vectors with the direction to the other player avoid expensive acos calls and give a fast approximate facing check.


```lua
ply:SomeHelper()
Reason: Method call avoids a global lookup and directly accesses the player meta, making it marginally faster than passing the player as an argument to a global function.
```


```lua
MsgN("Debug: ", someVar)
```
Reason: MsgN writes directly to the console without the formatting overhead of print, making it faster for hot‑path debugging.


```lua
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: Numeric for loop avoids iterator overhead and is fastest for sequential arrays.


```lua
-- Fast filter‑map pipeline for DarkRP lists
local function filter_map(list, pred, mapper)
    local out = {}
    for i = 1, #list do
        local v = list[i]
        if pred(v) then
            out[#out+1] = mapper(v)
        end
    end
    return out
end

-- Example: get names of all Civil Protection officers
local cpNames = filter_map(player.GetAll(),
    function(p) return p:getDarkRPVar("job") == "Civil Protection" end,
    function(p) return p:Nick() end)
```
Reason: Uses a single loop and avoids intermediate tables, reducing allocations and function call overhead compared to chaining fn.Filter and fn.Map.


OpenRouter error: Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (228/32) (code 502)


```lua
-- Fast per-player storage using a weak-keyed table
local plyData = setmetatable({}, {__mode = "k"})

-- Store data for a player
plyData[ply] = someValue

-- Read data (fast lookup)
local value = plyData[ply]
```
Reason: A weak-keyed table stores data in a regular Lua table, avoiding per-entity metatable lookups and making reads faster than accessing a field directly on the player entity.


```lua
-- Example of a fast-iterating table: sequential array
local values = { 10, 20, 30, 40, 50 }

for i = 1, #values do
    local v = values[i]
    -- do something with v
    print(v)
end
```
Reason: Sequential number-indexed arrays provide direct index access and cache-friendly iteration, making them faster than string-keyed maps which require hash lookups.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw r,g,b,a numbers avoids creating a Color object each frame, reducing overhead in hot draw loops.


```lua
-- Simple read query using GMod's SQLite API
local function GetPlayerData(ply)
    local sid = ply:SteamID64()
    local query = string.format("SELECT data FROM player_data WHERE steamid = %s", sql.SQLStr(sid))
    local result = sql.Query(query)
    if result and #result > 0 then
        return util.JSONToTable(result[1].data)
    end
    return nil
end
```

Reason: Local SQLite eliminates network round‑trips, so reads and writes are faster than remote MySQL on a single‑server setup.


```lua
local steamIDCache = {}

local function GetSteamID(ply)
    if not IsValid(ply) then return "BOT" end
    local sid = steamIDCache[ply]
    if not sid then
        sid = ply:SteamID()
        steamIDCache[ply] = sid
    end
    return sid
end

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIDCache[ply] = nil
end)
```
Reason: Caches each player's SteamID on first access, avoiding repeated costly calls to ply:SteamID().


```lua
local parts = {}
for i = 1, 10000 do
    parts[i] = "chunk" .. i
end
local bigString = table.concat(parts)
```
Reason: table.concat allocates the final string once, avoiding the O(n²) cost of repeated .. concatenation.


```lua
local function DrawFastRect(x, y, w, h, color)
    surface.SetDrawColor(color.r, color.g, color.b, color.a)
    surface.DrawRect(x, y, w, h)
end
```

Reason: surface.DrawRect skips the corner‑handling logic and extra function calls in draw.RoundedBox, making it faster for drawing plain rectangles.


```lua
hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello, World!")
end)
```
Reason: surface.* text helpers avoid the extra overhead of draw.DrawText/SimpleTextOutlined, making per‑frame text rendering faster.


```lua
local length = #myTable
```
Reason: The # operator gives the length of the sequential part of a table in O(1) time and is the standard way in Lua and Garry's Mod.


```lua
table.Empty(t)
```
Reason: table.Empty clears the existing table in place, avoiding the allocation and GC overhead of creating a new table with t = {}.


```lua
local set = {["apple"]=true, ["banana"]=true, ["cherry"]=true}
if set[someValue] then
    -- value exists
end
```
Reason: Using a table as a set gives O(1) lookup instead of the O(n) linear search performed by table.HasValue.


```lua
local myTable = { name = "John", age = 30, active = true }
```
Reason: Table constructor builds the table in a single allocation, avoiding multiple field assignments and hash lookups, which is faster for small known fields.


```lua
local function RandomSequential(t)
    return t[math.random(#t)]
end
```
Reason: Direct index access avoids iterating over the table, giving O(1) time instead of O(n).


```lua
-- Fast squaring in a tight loop
local x = 5  -- example value
for i = 1, 1e6 do
    local sq = x * x  -- multiplication is fastest
    -- use sq as needed
end
```
Reason: Multiplication is the fastest operation for squaring numbers in Lua, avoiding function calls and extra overhead.


```lua
for k, v in pairs(player.GetAll()) do
    -- v is the player object
end
Reason: This loop iterates over each currently connected player via player.GetAll().
```


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- process prop_physics entity
    end
end
```
Reason: ents.Iterator() yields entities one by one, avoiding the creation of a full entity table.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your Think logic here
end)
```
Reason: Registers a callback named "MyAddon.Think" to run every frame via the Think hook.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
    ent:SomeMethod()
end
```
Reason: IsValid checks that the entity exists and hasn't been removed, preventing errors from calling methods on a nil or invalid entity.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming MyAddon.Sync net message here
    -- Example: local data = net.ReadTable()
end)
```
Reason: Registers a net message handler for MyAddon.Sync using net.Receive.


```lua
-- Pre-allocate a single Angle instance outside the hot path
local zeroAngle = Angle(0, 0, 0)

-- In the hot path, reuse and zero it instead of creating a new Angle()
local function GetZeroedAngle()
    zeroAngle.p = 0
    zeroAngle.y = 0
    zeroAngle.r = 0
    return zeroAngle
end

-- Example usage in a tight loop
for i = 1, 10000 do
    local ang = GetZeroedAngle()
    -- use ang ...
end
```

Reason: Reusing a pre-allocated Angle and manually zeroing its components avoids repeated allocations and garbage collection overhead, which is significantly faster in hot paths.


```lua
local myColor = Color(255, 0, 0)
local c = myColor
```
Reason: Local variable access avoids global table and nested table lookups, making it the fastest for frequent reads.


```lua
-- Preferred way to get a player's job name in DarkRP
local jobName = ply:getDarkRPVar("job")
-- Or, if you need the full job table:
-- local jobTable = ply:getJobTable()
-- local jobName = jobTable.name
```

Reason: DarkRP stores the job name in a DarkRP variable, so `ply:getDarkRPVar("job")` is the official, network‑optimized accessor instead of the generic `GetNWString`.


```lua
local threshold = 100
local thresholdSqr = threshold * threshold
if vec1:DistToSqr(vec2) <= thresholdSqr then
    -- within threshold
end
```
Reason: DistToSqr returns the squared distance, allowing a fast threshold check without the costly square root.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- process ent
end
```
Reason: Using ipairs on ents.GetAll() is the wiki-recommended efficient way to iterate all entities.


```lua
-- Fast spatial query: entities within a radius of a player
local ply = Entity(1) -- replace with actual player entity
local radius = 500
local nearby = ents.FindInSphere(ply:GetPos(), radius)

for _, ent in ipairs(nearby) do
    -- process each nearby entity
    print(ent)
end
```
Reason: ents.FindInSphere uses the engine's spatial partition for a simple distance check, making it faster than FindInPVS for radius-based queries.


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local players = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: Iterating over player.GetAll() and checking squared distance avoids the overhead of ents.FindInSphere which scans all entities before filtering.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are optimized in Lua and avoid the overhead of manual condition checks, making them faster for tight counting loops.


```lua
-- Faster: single hook.Run with all players
local allPlayers = player.GetAll()
hook.Run("MyTick", allPlayers)

-- Slower: looping and calling hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTick", ply)
end
```
Reason: Calling hook.Run once with a table of all players avoids the overhead of repeated hook lookups and function calls for each player.


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

    local hp = ply:Health() -- cache once per frame

    -- Example draw calls using the cached value
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.RoundedBox(4, 10, 30, math.Clamp(hp, 0, 100) * 2, 20, Color(200, 0, 0))
    surface.SetDrawColor(0, 200, 0)
    surface.DrawRect(10, 55, hp, 5)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids three redundant function calls per frame, reducing overhead.


```lua
-- Cache the color once outside the paint hook
local white = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "ExamplePaint", function()
    -- Reuse the cached color
    surface.SetDrawColor(white)
    -- ... drawing code ...
end)
```
Reason: Avoid allocating a new Color object every frame by caching it once, reducing garbage collection overhead.


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


```lua
-- Cache LocalPlayer once per frame to avoid repeated lookups
local cachedPlayer

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

-- Example usage
local function DoSomethingWithPlayer()
    local ply = cachedPlayer
    if not IsValid(ply) then return end
    -- use ply here
end
```
Reason: Caching LocalPlayer in a Think hook eliminates repeated global function calls and table lookups each frame.


```lua
-- Fast check if two players are roughly looking at each other using aim vectors.
-- Returns true when both players aim within `cosThreshold` of the direction to the other.
-- `cosThreshold` is the cosine of the max allowed angle (e.g. 0.7071 for 45°).
function AreLookingAtEachOther(ply1, ply2, cosThreshold)
    cosThreshold = cosThreshold or 0.70710678 -- default ~45°
    if not (IsValid(ply1) and IsValid(ply2)) then return false end

    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()

    local dir12 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local dir21 = -dir12 -- opposite direction

    -- Dot product > cosThreshold means angle < threshold
    return aim1:Dot(dir12) > cosThreshold and aim2:Dot(dir21) > cosThreshold
end
```
Reason: Using dot products of normalized aim vectors with the direction to the other player avoids expensive `math.acos`; a simple threshold comparison on the cosine gives a fast "roughly looking at each other" test.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the metatable lookup required by the `:` syntax, making them marginally faster.


```lua
-- Faster debug output in a hot path
Msg("Debug: some value = " .. someValue .. "\n")
```
Reason: Msg writes directly to the console without the overhead of print's formatting and newline handling.


```lua
for i = 1, #tbl do
    local v = tbl[i]
    -- process v
end
```
Reason: Numeric for loop avoids iterator overhead and is fastest for sequential arrays.


Answer must contain 0 through 2 candidate loops.

```lua
-- Fast list pipeline for DarkRP (no fn library)
local M = {}

-- filter: keep elements where predicate returns true
function M.filter(tbl, pred)
    local out, n = {}, 0
    for i = 1, #tbl do
        local v = tbl[i]
        if pred(v, i) then
            n = n + 1
            out[n] = v
        end
    end
    return out
end

-- map: transform each element
function M.map(tbl, fn)
    local out = {}
    for i = 1, #tbl do
        out[i] = fn(tbl[i], i)
    end
    return out
end

-- reduce: fold left
function M.reduce(tbl, fn, init)
    local acc = init
    for i = 1, #tbl do
        acc = fn(acc, tbl[i], i)
    end
    return acc
end

-- compose multiple steps into a single pass (filter → map → reduce)
function M.pipeline(tbl, steps)
    -- steps is an array of {type="filter"/"map"/"reduce", fn=..., init=...}
    local acc = nil
    local hasInit = false
    for _, step in ipairs(steps) do
        if step.type == "filter" then
            local tmp, n = {}, 0
            for i = 1, #tbl do
                local v = tbl[i]
                if step.fn(v, i) then
                    n = n + 1
                    tmp[n] = v
                end
            end
            tbl = tmp
        elseif step.type == "map" then
            local tmp = {}
            for i = 1, #tbl do
                tmp[i] = step.fn(tbl[i], i)
            end
            tbl = tmp
        elseif step.type == "reduce" then
            if not hasInit then
                acc = step.init
                hasInit = true
            end
            for i = 1, #tbl do
                acc = step.fn(acc, tbl[i], i)
            end
            return acc
        end
    end
    return tbl
end

return M
```

Reason: Plain loops avoid the overhead of DarkRP's fn combinators (function wrapping, table creation per step) and a single-pass pipeline reduces intermediate tables, giving measurable speed gains in typical DarkRP workloads.


```lua
local cachedPlayers = {}

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

-- Update cache when a player fully joins or leaves
hook.Add("PlayerInitialSpawn", "PlayerCache_Refresh", refreshPlayerCache)
hook.Add("PlayerDisconnected", "PlayerCache_Refresh", refreshPlayerCache)

-- Example Think/Tick hook using the cached table
hook.Add("Think", "Example_UseCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Your per‑player logic here
    end
end)
```
Reason: Caching player.GetAll() and refreshing only on join/leave avoids the O(n) allocation every tick, reducing GC pressure and CPU usage.


```lua
-- Fast per-player storage using a numeric key (UserID) for O(1) reads/writes
local playerStore = {}

local function SetPlayerData(ply, key, value)
    local id = ply:UserID()
    local data = playerStore[id]
    if not data then
        data = {}
        playerStore[id] = data
    end
    data[key] = value
end

local function GetPlayerData(ply, key)
    local data = playerStore[ply:UserID()]
    return data and data[key] or nil
end

-- Example usage:
-- SetPlayerData(ply, "tempValue", 42)
-- local val = GetPlayerData(ply, "tempValue")
```

Reason: Using a separate table keyed by the player's numeric UserID avoids the entity metatable lookup overhead of `ply.someField`, providing faster read/write access for temporary per-player data.


Answer must contain 0 through 1 candidate loops.

```lua
-- Sequential array (fast iteration)
local arr = { "a", "b", "c", "d", "e" }
for i = 1, #arr do
    local v = arr[i]
    -- use v
end

-- String-keyed map (slower iteration)
local map = { foo = 1, bar = 2, baz = 3 }
for k, v in pairs(map) do
    -- use k, v
end
```
Reason: Sequential numeric arrays use contiguous memory and direct index access, making iteration faster than hash‑based string-keyed maps which require key hashing and lookup.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing individual RGBA numbers avoids Color object allocation and is faster in hot draw paths.


```lua
local steamid = "STEAM_0:1:123456"
local row = sql.QueryRow("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
if row then
    PrintTable(row)
else
    print("No data found")
end
```
Reason: Local SQLite runs in‑process, eliminating network latency and making reads/writes faster for a single server.


```lua
local steamIDCache = {}

local function GetSteamID(ply)
    if not IsValid(ply) then return "" end
    local cached = steamIDCache[ply]
    if cached then return cached end
    local sid = ply:SteamID()
    steamIDCache[ply] = sid
    return sid
end

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIDCache[ply] = nil
end)
```
Reason: Caches each player's SteamID on first call and invalidates on disconnect, avoiding repeated expensive SteamID() lookups.


```lua
-- Fast string building in Garry's Mod using a table buffer
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "part" .. i  -- each small piece
end
local bigString = table.concat(pieces)
```

Reason: Using a table to collect pieces and a single table.concat avoids the O(n²) cost of repeated .. concatenation.


```lua
-- Faster rectangle drawing for non-rounded boxes
surface.SetDrawColor(255, 255, 255, 255) -- set color once per frame or per batch
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect bypasses the radius logic and extra function calls in draw.RoundedBox, reducing per-draw overhead.


```lua
-- Fastest single-line text rendering per frame
local myFont = "DermaDefault"
local myText = "Hello, World!"
local x, y = 100, 100
local col = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "FastTextExample", function()
    surface.SetFont(myFont)
    surface.SetTextColor(col)
    surface.SetTextPos(x, y)
    surface.DrawText(myText)
end)
```
Reason: surface.SetFont/SetTextColor/SetTextPos/DrawText avoids the overhead of draw library wrappers and outline rendering, making it the fastest for single-line strings each frame.


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


```lua
-- Discard table contents quickly by assigning a new empty table
t = {}
```
Reason: t = {} is O(1) allocation while table.Empty(t) iterates over all keys (O(n)).


```lua
-- Using a hash set for O(1) lookup
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

local function HasValue(set, val)
    return set[val] ~= nil
end

-- Example usage
print(HasValue(mySet, "value2")) -- true
print(HasValue(mySet, "missing")) -- false
```
Reason: A table used as a hash set gives O(1) average lookup, while table.HasValue scans the list O(n).


```lua
-- Faster: table constructor with fields
local t1 = {a = 1, b = 2, c = 3}

-- Slower: create empty table then assign
local t2 = {}
t2.a = 1
t2.b = 2
t2.c = 3
```
Reason: Table constructor creates and populates the table in a single operation, avoiding repeated hash lookups and extra allocations.


```lua
local function fastRandom(tbl)
    return tbl[math.random(1, #tbl)]
end
```
Reason: Direct index access with math.random avoids the overhead of table.Random's iteration over the table.


```lua
local x = 5
for i = 1, 1000000 do
    local sq = x * x
    -- use sq
end
```
Reason: Multiplication (x * x) is the fastest way to square a number in Lua, avoiding function call overhead of math.pow or the exponentiation operator.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- code for each player
end
```
Reason: Using ipairs provides a clean sequential iteration over the table returned by player.GetAll().


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process each prop_physics entity
    print(ent)
end
```
Reason: ents.FindByClass returns only entities of the specified class, avoiding a full map entity table.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your Think logic here
end)
```
Reason: Registers a function to run every frame using the Think hook with the unique identifier MyAddon.Think.


```lua
if IsValid(ent) then
    -- ent is safe to use
    ent:SomeMethod()
end
```
Reason: IsValid(ent) returns true only if the entity exists and hasn't been removed, preventing errors from calling methods on invalid entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming MyAddon.Sync net message here
    -- Example: local data = net.ReadTable()
end)
```
Reason: Registers a net message handler for MyAddon.Sync using net.Receive.


local zeroAng = Angle(0, 0, 0)

-- Fast zeroed Angle for hot paths (reuse the same instance)
local function GetZeroAngle()
    zeroAng.p = 0
    zeroAng.y = 0
    zeroAng.r = 0
    return zeroAng
end

-- Example usage in a hot loop
for i = 1, 1000 do
    local ang = GetZeroAngle()
    -- use ang...
end

Reason: Reusing a single pre‑allocated Angle and resetting its components avoids the overhead of creating new userdata and reduces garbage collection pressure in performance‑critical code.


```lua
local threshold = 100
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- vectors are within the threshold distance
end
```
Reason: DistToSqr returns the squared distance, allowing a fast threshold check without the costly square root.


```lua
for _, ent in ents.Iterator() do
    -- Process each entity here
    print(ent)
end
```
Reason: Using ents.Iterator() avoids creating a temporary table and is the wiki-recommended efficient way to iterate over all entities in Garry's Mod.


```lua
local ply = Entity(1) -- replace with target player
local radius = 500
local nearbyEnts = ents.FindInSphere(ply:GetPos(), radius)

for _, ent in ipairs(nearbyEnts) do
    -- handle each nearby entity
end
```
Reason: ents.FindInSphere is consistently benchmarked as one of the fastest built-in spatial queries for radius-based searches in Garry's Mod.


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local players = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: Iterating over player.GetAll() and checking squared distance avoids scanning all entities, reducing overhead compared to ents.FindInSphere.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are optimized in Lua and generally faster than while loops for tight counting iterations.


```lua
-- Faster: single hook.Run with all players
hook.Run("MyTick", player.GetAll())

-- Slower: per-player hook.Run in a loop
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTick", ply)
end
```
Reason: Calling hook.Run once with a table of all players avoids the overhead of repeated hook lookups and function calls per player.


```lua
hook.Add("HUDPaint", "DrawHealthOptimized", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end
    local hp = ply:Health()
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 10, Color(255,255,255))
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, Color(255,255,255))
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 50, Color(255,255,255))
end)
```
Reason: Cache LocalPlayer():Health() once per frame to avoid three redundant method calls.


```lua
-- Cache the color once outside the paint hook
local white = Color(255, 255, 255)

hook.Add("HUDPaint", "OptimizedPaint", function()
    -- Reuse the cached color object
    surface.SetDrawColor(white)
    -- ... drawing code ...
end)
```
Reason: Creating a new Color object every frame allocates garbage; caching it once avoids allocation and reduces GC pressure.


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


```lua
local cachedPlayer

hook.Add("Think", "UpdateLocalPlayerCache", function()
    cachedPlayer = LocalPlayer()
end)

-- Example usage
if IsValid(cachedPlayer) then
    -- work with cachedPlayer instead of calling LocalPlayer()
end
```
Reason: Caching LocalPlayer in a local variable updated each frame avoids repeated global lookups and function calls, improving performance.


```lua
-- Fast "looking at each other" check using aim vectors (no math.acos)
-- Returns true if both players are roughly facing each other.
-- threshold: dot product threshold (1 = exactly same direction, 0 = perpendicular, -1 = opposite)
-- Typical value 0.7 ~ 45° cone.
function PlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7

    if not (IsValid(ply1) and IsValid(ply2)) then return false end
    if ply1 == ply2 then return false end

    -- Aim directions (unit vectors)
    local aim1 = ply1:EyeAngles():Forward()
    local aim2 = ply2:EyeAngles():Forward()

    -- Direction from each player to the other (unit vectors)
    local dir12 = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    local dir21 = (ply1:GetShootPos() - ply2:GetShootPos()):GetNormalized()

    -- Dot products: 1 = looking directly at, 0 = perpendicular, -1 = looking away
    local dot1 = aim1:Dot(dir12)
    local dot2 = aim2:Dot(dir21)

    return dot1 >= threshold and dot2 >= threshold
end
```
Reason: Uses cheap dot‑product comparisons of normalized aim vectors and inter‑player direction vectors, avoiding expensive angle calculations.


```lua
SomeHelper(ply)
```
Reason: Direct function call avoids metatable lookup and extra argument handling, making it slightly faster.


```lua
-- Faster debug output in a hot path
Msg("Debug: " .. someVar .. "\n")
```
Reason: Msg writes directly to the console without the overhead of print's formatting and newline handling.


```lua
local t = {1, 2, 3, 4, 5} -- large sequential array
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: Numeric for loop avoids iterator overhead and uses direct index access, making it the fastest for sequential arrays.


```lua
-- Faster list transform pipeline without DarkRP's fn library
local function filter(tbl, pred)
    local res = {}
    for i = 1, #tbl do
        local v = tbl[i]
        if pred(v) then res[#res + 1] = v end
    end
    return res
end

local function map(tbl, fn)
    local res = {}
    for i = 1, #tbl do
        res[i] = fn(tbl[i])
    end
    return res
end

-- Example usage: double even numbers
local numbers = {1,2,3,4,5,6,7,8,9,10}
local result = map(filter(numbers, function(x) return x % 2 == 0 end), function(x) return x * 2 end)
-- result == {4,8,12,16,20}
```
Reason: Plain loops avoid function call overhead and extra table allocations of fn combinators, giving better performance in DarkRP.


```lua
-- Cached player list, updated only on join/leave
local cachedPlayers = {}

-- Add player when they fully spawn
hook.Add("PlayerInitialSpawn", "CachePlayerList_Add", function(ply)
    table.insert(cachedPlayers, ply)
end)

-- Remove player when they disconnect
hook.Add("PlayerDisconnected", "CachePlayerList_Remove", function(ply)
    for i, p in ipairs(cachedPlayers) do
        if p == ply then
            table.remove(cachedPlayers, i)
            break
        end
    end
end)

-- Example Think/Tick hook using the cached table
hook.Add("Think", "Example_UseCachedPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Your per‑player logic here
    end
end)
```
Reason: Caches the player list and updates it only on PlayerInitialSpawn and PlayerDisconnected, avoiding ipairs(player.GetAll()) every tick.


```lua
local playerData = {}

local function SetData(ply, key, value)
    local id = ply:SteamID64()
    local tbl = playerData[id]
    if not tbl then
        tbl = {}
        playerData[id] = tbl
    end
    tbl[key] = value
end

local function GetData(ply, key)
    local tbl = playerData[ply:SteamID64()]
    return tbl and tbl[key]
end
```

Reason: Storing data in a global table keyed by SteamID64 avoids entity metatable overhead and allows local table reference caching for faster reads.


```lua
-- Faster iteration: sequential number-indexed array
local arr = { "a", "b", "c", "d" }
for i = 1, #arr do
    local v = arr[i]
    -- use v
end

-- Slower iteration: string-keyed map
local map = { foo = 1, bar = 2, baz = 3 }
for k, v in pairs(map) do
    -- use k, v
end
```
Reason: Sequential arrays use contiguous memory and numeric loops, avoiding hash lookups, making iteration faster than string-keyed maps.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate r,g,b,a numbers avoids Color object allocation and table lookups, making it faster in hot draw paths.


```lua
-- Using the built-in sql library (SQLite) for low-latency local storage
local result = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
if result then
    -- process result
end
```
Reason: Local SQLite (sql library) runs in-process, eliminating network round-trips, so reads/writes are faster than remote MySQL.


```lua
local steamIDCache = {}

local function GetSteamID(ply)
    if not IsValid(ply) then return "" end
    local cached = steamIDCache[ply]
    if cached then return cached end
    local sid = ply:SteamID()
    steamIDCache[ply] = sid
    return sid
end

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIDCache[ply] = nil
end)
```
Reason: Caches SteamID per player in a table to avoid repeated calls to ply:SteamID(), and clears entries on disconnect to prevent memory leaks.


```lua
-- Fast string building in Garry's Mod using a table and table.concat
local parts = {}
local add = parts  -- local reference for speed

-- Example: adding thousands of small strings
for i = 1, 10000 do
    add[#add + 1] = "piece" .. i .. " "
end

-- One final concatenation
local bigString = table.concat(parts)
```

Reason: Using a table to collect strings and a single table.concat avoids the O(n²) cost of repeated .. concatenation.


```lua
local surface = surface

-- Fast rectangle draw (no rounded corners)
local function DrawRectFast(x, y, w, h, col)
    surface.SetDrawColor(col.r, col.g, col.b, col.a)
    surface.DrawRect(x, y, w, h)
end

-- Usage example per frame:
-- DrawRectFast(10, 10, 100, 50, Color(255, 0, 0, 255))
```
Reason: surface.DrawRect bypasses the extra logic in draw.RoundedBox and directly issues a single quad draw call, reducing per-frame overhead for many rectangles.


```lua
-- Fast single-line text drawing using surface.* (lower-level, less overhead)
local fontName = "FastHUDFont"
surface.CreateFont(fontName, {
    font = "Roboto",
    size = 22,
    weight = 500,
    antialias = true,
})

local hudText = "Hello, Garry's Mod!"
local textW, textH = surface.GetTextSize(hudText)

hook.Add("HUDPaint", "FastSurfaceText", function()
    surface.SetFont(fontName)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(20, 20)          -- position once per frame
    surface.DrawText(hudText)           -- direct GPU draw, no extra layout
end)
```

Reason: surface.SetFont/SetTextPos/DrawText bypasses the higher-level draw library, avoiding per-frame font lookup, text wrapping, and outline calculations, making it the fastest way to render a static single-line string each frame.


```lua
local length = #myArray
```
Reason: The `#` operator is the standard and preferred way to obtain the length of a sequential array-like table in Lua (including Garry's Mod).


```lua
t = {}
```
Reason: t = {} creates a new table instantly, while table.Empty(t) must iterate and nil each entry, which is slower for large tables.


```lua
-- Using a set for O(1) membership test
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

local function hasValue(set, val)
    return set[val] == true
end

-- Example usage
print(hasValue(mySet, "value2")) -- true
print(hasValue(mySet, "missing")) -- false
```
Reason: A hash‑based set gives O(1) lookup, while table.HasValue scans the list O(n).


```lua
-- Faster: table constructor with fields
local t1 = {a = 1, b = 2, c = 3}

-- Slower: create empty table then assign
local t2 = {}
t2.a = 1
t2.b = 2
t2.c = 3
```
Reason: Table constructor creates and populates the table in a single operation, avoiding repeated hash lookups and allocations.


```lua
local function fastRandom(tbl)
    return tbl[math.random(1, #tbl)]
end
```
Reason: Directly indexing with math.random avoids the internal iteration of table.Random, making it faster for sequential tables.


```lua
local x = 5
for i = 1, 1000000 do
    local sq = x * x
end
```
Reason: Multiplying a number by itself (x * x) is the fastest way to square in Lua, avoiding function call overhead of math.pow or the exponentiation operator.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- your code here
end
```
Reason: Using ipairs for sequential iteration over the player list returned by player.GetAll().


```lua
local index = 1
while true do
    local ent = ents.GetByClass("prop_physics", index)
    if not ent then break end
    -- Process entity here
    index = index + 1
end
```
Reason: This loop uses sequential indexing with `ents.GetByClass` to iterate through entities without storing them in a table, avoiding memory overhead.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: Registers a callback for the Think hook using the specified identifier via hook.Add.


```lua
IsValid(ent)
```
Reason: `IsValid` checks if the entity reference is still active and valid in Garry's Mod.


```lua
net.Receive("MyAddon.Sync", function(data)
    -- Handle the message here
end)
```
Reason: Uses net.Receive to register a handler for the MyAddon.Sync net message.


```lua
myaddon.color = "red"
print(myaddon.color)
```
Reason: Flat variables require a single table lookup, while nested tables require multiple, making flat variables faster for frequent reads.


```lua
ply:GetJob()
```
Reason: `GetJob()` is a direct DarkRP API method for retrieving a player's job, optimized and intended for this purpose compared to `GetNWString`.


```lua
function IsWithinThreshold(vec1, vec2, threshold)
    local diff = vec1 - vec2
    return diff:Dot(diff) <= threshold * threshold
end
```
Reason: Using the squared distance via Dot product avoids the computationally expensive square root operation, making the threshold check more efficient.


```lua
local ent = next(entities)
while ent do
    -- Process entity 'ent' here
    ent = next(entities, ent)
end
```
Reason: This uses the `next` iterator which is memory-efficient and recommended for entity iteration in Garry's Mod, avoiding the overhead of storing all entities in memory at once.


```lua
local entities = FindInSphere(player:GetPos(), 100)
```
Reason: FindInSphere is a fast built-in spatial query that checks entities within a radius, optimized for performance compared to PVS-based methods.


```lua
function findPlayersInRadius(targetPos, radius)
    local players = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:IsValid() and (ply:GetPos() - targetPos):Length() < radius then
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: Directly iterates over players instead of all entities, reducing unnecessary checks and improving performance.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The `for` loop is optimized for numeric ranges in Lua, reducing overhead compared to `while` which requires explicit condition checks and counter increments each iteration.


```lua
hook.Run("MyHook", playerTable)
```
Reason: Reducing the number of function calls by passing all players in a single hook.Run invocation minimizes overhead compared to per-player calls.


```lua
local health = LocalPlayer():Health()
-- Use 'health' in all three draw calls instead of calling LocalPlayer():Health() each time
```

Reason: Caching the health value once reduces redundant function calls, minimizing overhead and improving performance.


```lua
local sin = math.sin
for i = 1, 1000 do
    local val = sin(i)
end
```
Reason: Caching `math.sin` in a local variable reduces global table lookup overhead in tight loops.


```lua
local player = LocalPlayer()
-- Use 'player' instead of LocalPlayer() in subsequent calls
```
Reason: Caching LocalPlayer() in a local variable reduces repeated function calls, improving performance.


```lua
SomeHelper(ply)
```
Reason: Passing fewer arguments can reduce overhead, making SomeHelper(ply) potentially faster if the helper doesn't require the self parameter.


```lua
for i, v in ipairs(array) do
    -- process v
end
```
Reason: ipairs is optimized for sequential integer-keyed tables, minimizing overhead compared to pairs (which iterates all keys) or numeric for (which requires manual index management).


```lua
function fastPipeline(list, filter, map)
    local result = {}
    for _, item in ipairs(list) do
        if filter(item) then
            table.insert(result, map(item))
        end
    end
    return result
end
```
Reason: Combining filter and map into a single loop reduces iteration overhead and function call count compared to separate combinator chains.


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

hook.Add("PlayerConnect", "UpdateCachedPlayers", function(ply)
    table.insert(cachedPlayers, ply)
end)

hook.Add("PlayerDisconnect", "UpdateCachedPlayers", function(ply)
    for i, v in ipairs(cachedPlayers) do
        if v == ply then
            table.remove(cachedPlayers, i)
            break
        end
    end
end)
```
Reason: Caching the player list reduces redundant calls to `player.GetAll()` by updating only on player join/leave events, which are less frequent than every tick.


```lua
local arr = {10, 20, 30}
for i, v in ipairs(arr) do
    print(v)
end
```
Reason: Sequential number-indexed arrays use contiguous memory and `ipairs` is optimized for them, making iteration faster than string-keyed maps.


```lua
surface.SetDrawColor(255, 0, 0)
```
Reason: Using separate r, g, b numbers is faster than a Color object as it avoids object creation overhead in performance-critical paths.


```lua
local db = sqlite3.open("playerdata.db")
local res = db:exec("SELECT * FROM players WHERE id = ?", {123})
db:close()
```
Reason: Local SQLite avoids network latency by handling reads/writes directly on the same machine, while remote MySQL introduces network overhead even on the same server.


```lua
local steamid_cache = {}
for _, ply in ipairs(players) do
    if not steamid_cache[ply] then
        steamid_cache[ply] = ply:SteamID()
    end
    local steamid = steamid_cache[ply]
    -- Use steamid here
end
```
Reason: Caching SteamIDs in a table avoids redundant calls to `ply:SteamID()`, reducing overhead in hot paths by reusing stored values.


```lua
local parts = {}
for i = 1, #pieces do
    table.insert(parts, pieces[i])
end
local result = table.concat(parts)
```

Reason: Using a table to accumulate parts and `table.concat` avoids the O(n^2) time complexity of repeated string concatenation with `..`, which creates new strings repeatedly.


```lua
draw.Rectangle(x, y, w, h, color)
```
Reason: `draw.Rectangle` avoids the overhead of rounding calculations when radius is 0, making it slightly faster for non-rounded rectangles.


```lua
surface.DrawText("YourText", x, y, color)
```
Reason: surface.DrawText is optimized for frequent text rendering and avoids the overhead of draw module functions, making it faster for single-line updates every frame.


```lua
return #myTable
```
Reason: The `#` operator is the preferred and idiomatic way to get the length of a sequential array-like table in Lua.


```lua
t = {}
```
Reason: Reassigning `t = {}` creates a new empty table directly, which is faster than `table.Empty(t)` for large tables as it avoids iterating through existing elements.


```lua
-- Example usage:
local set = {}
set[value] = true -- Add to set
if set[checkValue] then -- Check existence
  -- Value exists
end
```
Reason: Using a table as a set with key lookups (O(1) average time) is faster than table.HasValue (O(n) time) for large lists.


```lua
local t = {a=1, b=2, c=3}
```
Reason: Initializing the table in the constructor is more efficient as it avoids multiple assignment operations.


```lua
function getRandom(t) return t[math.random(#t)] end
```
Reason: Directly using math.random with the table's length avoids the overhead of table.Random's function call and internal checks.


```lua
x * x
```
Reason: Multiplication is a single operation with no function call overhead, making it faster than alternatives like math.pow(x, 2) in tight loops.


```lua
for k, v in pairs(player.GetAll()) do
    -- Process each player 'v' here
end
```
Reason: `player.GetAll()` returns a table of connected players, and `pairs` iterates through each entry, allowing access to each player object.


Skipped: free model produced no text earlier in this run (will quarantine after run if pattern holds).


OpenRouter error: Internal Server Error (code 500)


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback logic here
end)
```
Reason: Registers a Think hook callback with the unique identifier "MyAddon.Think" to run every frame.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```

Reason: The IsValid() function checks if the entity exists and hasn't been removed, preventing errors from nil or invalid references.


```lua
net.Receive("MyAddon.Sync", function()
    -- Handle the received data here
end)
```
Reason: Registers a handler function for the "MyAddon.Sync" net message using Garry's Mod's net library.


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

-- In hot path:
zeroAngle:SetUnnormalized(0, 0, 0)
-- or
zeroAngle.p, zeroAngle.y, zeroAngle.r = 0, 0, 0
```

Reason: Reusing a pre-allocated Angle object and resetting its values avoids the overhead of creating a new Angle instance each time, which is more efficient in performance-critical code.


```lua
-- Preferred: cache in a local variable
local color = myaddon.config.color

-- Use the local for frequent reads
print(color)
```

Reason: Local variables are faster to access than nested tables because they avoid multiple hash lookups, reducing overhead in frequently read code.


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

Reason: The getDarkRPVar method is the official DarkRP API for accessing job data, ensuring compatibility and proper integration with the framework's systems.


```lua
local distSqr = vec1:DistToSqr(vec2)
if distSqr < threshold * threshold then
    -- Vectors are within threshold distance
end
```
Reason: Using DistToSqr avoids sqrt calculation for efficiency, comparing squared distance to squared threshold.


```lua
for ent, class in ents.Iterator() do
    -- Process each entity here
end
```

Reason: Uses the efficient C-side iterator `ents.Iterator()` to loop through all entities without creating a table, as recommended by the Garry's Mod wiki for performance.


```lua
local playerPos = ply:EyePos()
local radius = 128
local min = playerPos - Vector(radius, radius, radius)
local max = playerPos + Vector(radius, radius, radius)
local entities = ents.FindInBox(min, max)
```
Reason: FindInBox uses axis-aligned bounding box checks which are computationally cheaper than sphere calculations or PVS traversal, making it one of the fastest built-in spatial queries.


```lua
function GetPlayersInRadius(pos, radius)
    local players = {}
    local r2 = radius * radius
    for _, ply in ipairs(player.GetHumans()) do
        if (ply:GetPos() - pos):LengthSqr() <= r2 then
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: Directly iterates over all players and uses squared distance comparison to avoid expensive square root calculations, which is faster than ents.FindInSphere for large player counts.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric for loop is optimized in Lua for counting iterations, reducing overhead compared to manually managing a while loop's counter and condition.


```lua
-- Faster: Call hook once with all players
hook.Run("CustomTickHook", player.GetAll())

-- Slower: Loop players and call hook per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("CustomTickHook", ply)
end
```

Reason: Calling hook.Run once with all players reduces function call overhead and allows the hook handler to process all players in a single invocation, which is more efficient than multiple hook calls.


```lua
hook.Add("HUDPaint", "OptimizedHUD", function()
    local health = LocalPlayer():Health()
    draw.Text({text = "Health: " .. health, ...})
    draw.Text({text = "HP: " .. health, ...})
    draw.Text({text = "Current: " .. health, ...})
end)
```
Reason: Caching LocalPlayer():Health() in a local variable reduces redundant function calls, improving performance by avoiding repeated lookups.


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

hook.Add("HUDPaint", "MyPaintHook", function()
    surface.SetDrawColor(white)
    -- drawing code here
end)
```

Reason: Pre-creating the Color object outside the loop avoids repeated table allocations, reducing garbage collection overhead and improving performance.


```lua
local sin = math.sin
for i = 1, 10000 do
    someValue = sin(someArgument)
end
```
Reason: Caching math.sin in a local variable reduces table lookup overhead in the loop, improving performance.


```lua
local cached_ply
local function getLocalPlayer()
    if not cached_ply or not cached_ply:IsValid() then
        cached_ply = LocalPlayer()
    end
    return cached_ply
end
```
Reason: Caches the LocalPlayer in a local variable to avoid repeated global lookups, checking validity to handle edge cases like player disconnects.


```lua
SomeHelper(ply)
```
Reason: Direct function calls are slightly faster than method calls in Lua due to avoiding metatable lookups, making SomeHelper(ply) the preferred style for performance.


```lua
Msg("Debug: " .. tostring(value) .. "\n")
```

Reason: Msg is a lower-level GMod function that writes directly to the console without the overhead of print's formatting and multiple return value handling, making it significantly faster in performance-critical code paths.


```lua
local t = {1, 2, 3, 4, 5, ...} -- large sequential array
for i = 1, #t do
    local value = t[i]
    -- process value
end
```
Reason: Numeric for is fastest for sequential arrays as it uses direct index access with no iterator overhead, unlike ipairs/pairs which involve function calls.


```lua
local cachedPlayers = {}

-- Populate cache on server start
for _, ply in ipairs(player.GetAll()) do
    cachedPlayers[ply:SteamID()] = ply
end

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

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

hook.Add


```lua
local playerCache = {}

hook.Add("PlayerDisconnected", "CacheCleanup", function(ply)
    playerCache[ply] = nil
end)

-- Writing data
playerCache[ply] = playerCache[ply] or {}
playerCache[ply].someField = value

-- Reading data
local value = playerCache[ply] and playerCache[ply].someField
```

Reason: Using a separate table indexed by the player entity avoids metatable overhead and C++ to Lua marshaling, providing faster direct table lookups compared to accessing fields on the player object directly.


```lua
-- Faster: Sequential number-indexed array
local array = { "apple", "banana", "cherry" }
for i, value in ipairs(array) do
    print(i, value)
end

-- Slower: String-keyed map
local map = { fruit1 = "apple", fruit2 = "banana", fruit3 = "cherry" }
for key, value in pairs(map) do
    print(key, value)
end
```
Reason: Sequential arrays with ipairs() are faster because Lua optimizes iteration over numeric indices, while pairs() on string-keyed tables requires hash lookups and is less efficient.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```

Reason: Passing individual r, g, b, a numbers directly to surface.SetDrawColor is faster than creating a Color object each time, especially in hot draw paths where the function is called frequently.


```lua
local db = sql.Open("garrysmod/data/players.db")
if not db then return end

local query = db:query("SELECT * FROM player_data WHERE steamid = '" .. ply:SteamID() .. "'")
query:start()
local result = query:getData()
```

Reason: Local SQLite has no network overhead, making it significantly lower latency than remote MySQL for a single-server setup.


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

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

Reason: Uses a weak table to cache SteamID results per player, avoiding redundant calls and preventing memory leaks by allowing garbage collection of unused entries.


```lua
-- Slow approach (O(n^2) due to repeated string creation)
local result = ""
for i = 1, 10000 do
    result = result .. "piece" .. i
end

-- Fast approach (O(n) with table.concat)
local parts = {}
for i = 1, 10000 do
    table.insert(parts, "piece" .. i)
end
local result = table.concat(parts)
```

Reason: table.concat is more efficient because it avoids creating intermediate strings during concatenation, reducing time complexity from O(n^2) to O(n).


```lua
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(0, 0, 100, 100)
```

Reason: Using surface.DrawRect is faster than draw.RoundedBox(0, ...) because it directly draws a filled rectangle without the overhead of corner rounding calculations, even when the radius is zero.


```lua
surface.SetFont("DermaLarge")
surface.SetText("Hello World")
surface.SetDrawColor(255, 255, 255, 255)
surface.SetPos(100, 100)
surface.DrawText()
```

Reason: Using `surface.SetText` and `surface.DrawText` is faster than `draw.DrawText` because it directly interfaces with the rendering API, avoiding the overhead of higher-level draw functions.


```lua
#myTable
```

Reason: The # operator is the standard and efficient way to get the length of a sequential array-like table in Lua, as it directly returns the number of consecutive integer keys starting from 1.


```lua
-- Faster approach for discarding a large sequential table
local t = {}
-- ... populate t with many elements ...

-- Instead of table.Empty(t), use:
t = {}
```

Reason: Reassigning `t = {}` is faster because it creates a new table in O(1) time, while `table.Empty(t)` must iterate and nil all existing elements, which is O(n) for large tables.


```lua
-- Using a set (O(1) average lookup)
local set = {[1] = true, [2] = true, [3] = true}
if set[value] then
    -- Value exists in the set
end
```

Reason: Using a table with keys for set membership allows O(1) average-time lookups via key existence checks, whereas table.HasValue on a list requires O(n) linear iteration through all elements.


```lua
local t = {a = 1, b = 2, c = 3}
```

Reason: Using the table constructor is faster because it creates and initializes the table in a single operation, avoiding multiple separate assignments.


```lua
function FastRandomElement(tbl)
    local len = #tbl
    if len == 0 then return nil end
    return tbl[math.random(1, len)]
end
```

Reason: Uses O(1) index access with # and math.random instead of table.Random's O(n) linear search, making it significantly faster for sequential tables.


```lua
x * x
```

Reason: Multiplication is faster than exponentiation in Lua, and x * x is the most efficient way to square a number in a tight loop.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here for each player
end
```

Reason: Using `ipairs` with `player.GetAll()` is the modern, efficient method for iterating over all connected players in order, ensuring each player is visited exactly once.


```lua
for _, ent in ipairs(ents.GetAll()) do
    if ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: Uses ents.GetAll() to iterate through all entities and filters for prop_physics class without pre-building a separate table.


```lua
MyAddon = MyAddon or {}
MyAddon.Think = function()
	-- Your think logic here
end
hook.Add("Think", "MyAddon.Think", MyAddon.Think)
```
Reason: Registers a Think hook callback under the identifier MyAddon.Think for use in Garry's Mod.


```lua
if IsValid(ent) and not ent:IsDestroyable() then
    ent:SomeMethod()
end
```
Reason: IsValid checks if the entity reference is still valid and exists in the game world, preventing errors from calling methods on removed or null entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming net message here
    local data = net.ReadString(len) -- Example: read a string from the message
    print("Received MyAddon.Sync from", ply:Nick(), "with data:", data)
end)
```
Reason: This demonstrates how to register a net message handler for "MyAddon.Sync" in Garry's Mod Lua using net.Receive, which listens for incoming network messages and processes them with a callback function.


```lua
-- Faster: use a pre-zeroed Angle stored in a variable (reused, not reconstructed)
local zeroAngle = Angle(0, 0, 0)

-- In hot path, use the cached zeroed Angle
local function GetZeroAngle()
    return zeroAngle
end
```
Reason: Reusing a pre-constructed zeroed Angle avoids repeated memory allocation and garbage collection overhead in hot paths.


```lua
local color = myaddon.config.color
```

Reason: Local variables are faster than table lookups because they avoid the overhead of nested table access and global lookups.


```lua
ply:GetJob()
```
Reason: GetJob() is the preferred API to get a player's job name in DarkRP as it returns the job table directly, avoiding the unreliable NWString method.


```lua
local distanceSquared = (pos1 - pos2):LengthSqr()
if distanceSquared < threshold * threshold then
    -- within threshold
end
```
Reason: Using LengthSqr() avoids the expensive sqrt operation required by Length() when only comparing distances against a threshold.


```lua
for _, entity in ipairs(ents.GetAll()) do
    -- Process each entity
end
```
Reason: Uses ipairs with ents.GetAll() which is the recommended efficient iterator for entity iteration in Garry's Mod Lua.


```lua
local function GetEntitiesNearPlayer(ply, radius)
    local pos = ply:GetPos()
    local found = {}
    for _, ent in ipairs(ents.FindInSphere(pos, radius)) do
        if ent:IsValid() then
            table.insert(found, ent)
        end
    end
    return found
end
```
Reason: FindInSphere is a fast built-in spatial query using the engine's optimized sphere check, commonly benchmarked as one of the quickest alternatives to FindInPVS for nearby entity lookups.


```lua
-- Faster player radius check using player iterator instead of ents.FindInSphere
local function GetPlayersInRadius(pos, radius)
    local players = {}
    for _, v in ipairs(player.GetAll()) do
        if v:GetPos():DistToSqr(pos) <= radius * radius then
            table.insert(players, v)
        end
    end
    return players
end
```

Reason: Using player.GetAll() with DistToSqr avoids the overhead of ents.FindInSphere creating entity objects and then filtering, since we only need players and can skip the sphere query entirely.


```lua
local n = 1000
local i = 1
while i <= n do
    -- loop body
    i = i + 1
end
```
Reason: while loops with manual increment avoid the overhead of the for loop's iterator function and are generally faster for simple counting in Garry's Mod Lua.


```lua
-- Slower: loop each player and call hook.Run per player
hook.Add("Think", "NotifyEachPlayerSlow", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("PlayerTickNotify", ply)
    end
end)

-- Faster: call hook.Run once with all players
hook.Add("Think", "NotifyAllPlayersFast", function()
    hook.Run("PlayerTickNotify", player.GetAll())
end)
```
Reason: Calling hook.Run once with all players avoids the overhead of iterating and multiple hook dispatches, making it faster than looping and calling per player.


```lua
hook.Add("HUDPaint", "FasterHealthDraw", function()
    local health = LocalPlayer():Health()
    -- Use health variable for three draw calls instead of calling LocalPlayer():Health() each time
    -- Example draw calls (replace with actual drawing code):
    draw.RoundedBox(0, 10, 10, health, 20, Color(255, 0, 0))
    draw.SimpleText("Health: " .. health, "HealthFont", 10, 35, Color(255, 255, 255))
    draw.RoundedBox(0, 10, 55, health * 0.5, 10, Color(0, 255, 0))
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids redundant function calls and table lookups, improving performance by reducing the number of times the expensive method is invoked.


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

hook.Add("Paint", "FastWhitePaint", function()
    draw.Color(white.r, white.g, white.b, white.a)
    -- or use surface.SetDrawColor(white) if drawing shapes
end)
```
Reason: Pre-creating the Color object outside the paint loop avoids repeated table allocations and function calls on every frame, improving performance.


```lua
-- Micro-optimization: cache math.sin locally to avoid repeated table lookups
local sin = math.sin

-- Hot loop using cached function
for i = 1, 1000000 do
    local result = sin(i * 0.01)
end
```
Reason: Caching math.sin in a local variable avoids repeated table lookups in the hot loop, reducing overhead by one lookup per iteration.


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

-- Use the cached reference in your frame think hook or update loop
hook.Add("Think", "MyFasterPlayerAccess", function()
    if not IsValid(player) then
        player = LocalPlayer()
    end

    -- Use 'player' instead of LocalPlayer() throughout this frame
    -- Your code here...
end)

-- Alternative: cache in a variable that updates on player spawn
local cachedPlayer = LocalPlayer()

hook.Add("PlayerSpawn", "UpdateCachedPlayer", function(ply)
    if ply == LocalPlayer() then
        cachedPlayer = ply
    end
end)

hook.Add("Think", "UseCachedPlayer", function()
    if not IsValid(cachedPlayer) then
        cachedPlayer = LocalPlayer()
    end
    -- Use cachedPlayer instead of LocalPlayer()
end)
```

Reason: LocalPlayer() is a global function lookup that's slower than using a cached local reference. By storing the player object in a local variable and updating it only when necessary (on spawn or when invalid), we avoid repeated global function calls in performance-critical code like Think hooks.


```lua
-- Fast check if two players are roughly looking at each other
-- Uses dot product of aim vectors instead of angle calculations
local function ArePlayersLookingAtEachOther(p1, p2, tolerance)
    if not IsValid(p1) or not IsValid(p2) then return false end

    -- Get eye positions and aim vectors
    local pos1 = p1:EyePos()
    local pos2 = p2:EyePos()
    local dir1 = p1:GetForward()
    local dir2 = p2:GetForward()

    -- Vector from player 1 to player 2
    local toOther = (pos2 - pos1):GetNormalized()

    -- Dot product: positive means roughly facing each other
    -- tolerance is how strict to be (0.7 ~ 45 degrees, 0.9 ~ 25 degrees)
    local dot1 = dir1:Dot(toOther)
    local dot2 = dir2:Dot(-toOther)

    return dot1 > tolerance and dot2 > tolerance
end

-- Usage example:
-- if ArePlayersLookingAtEachOther(Player(1), Player(2), 0.7) then
--     print("Players are looking at each other!")
-- end
```
Reason: Uses dot product comparison with normalized vectors to avoid expensive math.acos calls, checking if both players' forward vectors have positive components toward each other within a tolerance threshold.


```lua
-- Preferred: SomeHelper(ply)
-- Call the helper as a standalone function rather than a method
SomeHelper(ply)
```

Reason: Using a standalone function call `SomeHelper(ply)` is generally faster than `ply:SomeHelper()` because the colon syntax requires Lua to perform additional work to resolve the method lookup and pass the table as the first argument, while a direct function call avoids this overhead.


```lua
MsgN("Debug: ", value)
```
Reason: MsgN is faster than print in Garry's Mod as it writes directly to the console without the overhead of string formatting and argument parsing.


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


```lua
-- Faster functional pipeline for DarkRP using local table operations
local function pipe(...)
    local args = {...}
    local t = table.remove(args)
    for i = #args, 1, -1 do
        local fn = args[i]
        if type(fn) == "function" then
            t = fn(t)
        elseif type(fn) == "table" and fn[1] == "filter" then
            local pred = fn[2]
            local out = {}
            for i = 1, #t do
                if pred(t[i]) then out[#out + 1] = t[i] end
            end
            t = out
        elseif type(fn) == "table" and fn[1] == "map" then
            local mapper = fn[2]
            local out = {}
            for i = 1, #t do out[i] = mapper(t[i]) end
            t = out
        end
    end
    return t
end

-- Usage:
-- local result = pipe(
--     {1, 2, 3, 4, 5},
--     {"filter", function(v) return v % 2 == 0 end},
--     {"map", function(v) return v * 2 end}
-- )
```

Reason: Uses direct table iteration with local variables and avoids DarkRP's fn library overhead by implementing inline filter/map operations with numeric for loops.


```lua
-- Cached player list that only updates on join/leave
local cachedPlayers = {}
local playerCount = 0

local function RefreshPlayerList()
    cachedPlayers = player.GetAll()
    playerCount = #cachedPlayers
end

-- Initialize on startup
RefreshPlayerList()

-- Update cache when players join or leave
hook.Add("PlayerInitialSpawn", "CachePlayers_OnJoin", function()
    RefreshPlayerList()
end)

hook.Add("PlayerDisconnected", "CachePlayers_OnLeave", function()
    RefreshPlayerList()
end)

-- Use the cached list in Think/Tick hooks
hook.Add("Think", "MyThinkHook", function()
    for i = 1, playerCount do
        local ply = cachedPlayers[i]
        -- Your per-player logic here
    end
end)
```

Reason: Caches the player list and only refreshes it on PlayerInitialSpawn and PlayerDisconnected events instead of calling player.GetAll() every tick, reducing unnecessary table allocations and iterations.


```lua
-- Use a table indexed by player for O(1) reads without metatable overhead
local PlayerData = {}

-- Write: PlayerData[ply][field] = value
-- Read: local value = PlayerData[ply][field]

-- Alternative: pre-allocate common fields for even faster access
local PlayerCache = {}
PlayerCache[ply] = PlayerCache[ply] or { health = 0, ammo = 0, score = 0 }

-- Direct field access is fastest: PlayerCache[ply].health
```

Reason: Direct table indexing avoids metatable lookups and property resolution overhead, providing faster reads than entity field access.


```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 integer keys which Lua optimizes with fast numeric iteration via `ipairs` and `#` length operator, while string-keyed maps require hash lookups for each access making them slower for fixed collections.


```lua
surface.SetDrawColor(255, 0, 0)
```
Reason: Passing separate r,g,b numbers avoids creating a Color object, which is faster in hot draw paths.


```lua
local sql = sql
sql.Query("CREATE TABLE IF NOT EXISTS players (steamid TEXT PRIMARY KEY, name TEXT, score INTEGER)")
sql.Query("INSERT OR REPLACE INTO players (steamid, name, score) VALUES ('STEAM_0:1:12345678', 'PlayerName', 100)")
local result = sql.Query("SELECT name, score FROM players WHERE steamid = 'STEAM_0:1:12345678'")
```

Reason: Local SQLite has lower latency than remote MySQL because it avoids network overhead and is optimized for single-server use cases.


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

local function GetCachedSteamID(ply)
    if not IsValid(ply) then return nil end
    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 to prevent memory leaks.


```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 string copying on each operation.


```lua
local draw_rounded_box_0 = draw.RoundedBox
local surface_draw_rect = surface.DrawRect
local draw_color = draw.Color

-- Faster alternative to draw.RoundedBox(0, x, y, w, h, color)
-- Uses surface.DrawRect directly, avoiding the overhead of rounded box calculations
local function FastBox(x, y, w, h, col)
    if col then
        draw_color(col.r, col.g, col.b, col.a)
    end
    surface_draw_rect(x, y, w, h)
end

-- Usage: FastBox(x, y, width, height, color)
-- Example: FastBox(100, 100, 50, 30, Color(255, 0, 0))
```

Reason: Uses surface.DrawRect directly which avoids the internal vertex calculations and mesh operations that draw.RoundedBox performs even with 0 corner radius, reducing CPU overhead per frame.


```lua
-- Faster text drawing in Garry's Mod client Lua
-- Use draw.SimpleTextOutlined with pre-cached font and minimal outline for single-line strings

local fontName = "DermaLarge"
local text = "Hello World"
local x, y = 100, 100
local colText = Color(255, 255, 255)
local colOutline = color_black
local outlineSize = 1

-- Cache font once
hook.Add("OnScreenSizeChanged", "CacheFont", function()
    surface.CreateFont(fontName, {
        font = "DermaLarge",
        size = 24,
        weight = 500,
        antialias = true
    })
end)

-- Draw every frame
hook.Add("HUDPaint", "DrawFastText", function()
    draw.SimpleTextOutlined(text, fontName, x, y, colText, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, outlineSize, colOutline)
end)
```

Reason: draw.SimpleTextOutlined is faster than surface.DrawText for single-line strings when the font is pre-cached, as it avoids the overhead of setting up text objects and provides optimized rendering for simple outlined text.


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


```lua
-- Generally faster approach: table.Empty(t)
local t = {}
table.insert(t, 1)
table.insert(t, 2)
table.insert(t, 3)

-- Option 1: table.Empty(t) - modifies in place
table.Empty(t)

-- Option 2: t = {} - creates new table (slower for large tables)
-- t = {}
```
Reason: table.Empty(t) is generally faster because it clears the existing table in-place without creating a new table object, avoiding memory allocation overhead and preserving any references to the original table.


```lua
local set = { a = true, b = true, c = true }
local exists = set[value] ~= nil
```
Reason: Using a table as a dictionary with boolean values provides O(1) lookup time, which is faster than table.HasValue's O(n) linear search through a list.


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

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

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 selection for sequential tables (1..#t)
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 works optimally for sequential integer-keyed tables.


```lua
local x = 0
for i = 1, 1000 do
    x = x * x
end
```
Reason: Direct multiplication is the fastest way to square a number in Lua, avoiding function call overhead.


```lua
for _, player in ipairs(player.GetAll()) do
    -- do something with player
end
```
Reason: Using ipairs with player.GetAll() is the modern, more efficient approach for iterating over the player list in Garry's Mod Lua.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    print(ent)
end
```
Reason: ents.FindByClass retrieves only prop_physics entities, avoiding ents.GetAll which would build a table of every entity in the map.


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

end)
```
Reason: Registers a Think hook callback with the unique identifier MyAddon.Think.


```lua
if not IsValid(ent) then return end
```
Reason: IsValid ensures ent is a non-NULL, valid entity not pending removal, preventing errors when calling methods.


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


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

entity:SetAngles(ZERO_ANGLE)
```
Reason: Reusing a pre-allocated zero Angle avoids repeated allocations and GC overhead compared to constructing a new Angle() each time.


```lua
local color = myaddon.config.color
local read = color
```
Reason: Flat local variables are stored in registers and avoid repeated nested table lookups, making frequent reads faster than global or nested table access.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: getDarkRPVar is DarkRP's official networked variable accessor, preferred over raw GetNWString for job.


```lua
if v1:DistToSqr(v2) < maxDist * maxDist then end
```
Reason: DistToSqr compares squared distance, avoiding costly sqrt while still allowing threshold checks.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- visit each entity
end
```
Reason: ipairs on ents.GetAll() is the GMod wiki-recommended efficient iterator for sequentially indexed entity tables.


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
```
Reason: ents.FindInSphere uses the engine spatial partition with a cheap distance check, commonly benchmarking faster than box/cone and avoiding PVS overhead.


```lua
local function GetPlayersInRadius(pos, radius)
    local found = {}
    local r2 = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if pos:DistToSqr(ply:GetPos()) <= r2 then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: player.GetAll() is far smaller than the full entity list, so iterating players with squared distance checks avoids ents.FindInSphere overhead and unnecessary entity filtering.


```lua
for i = 1, n do
end
```
Reason: numeric for loops are generally faster in Lua due to VM optimizations and precomputed loop bounds.


```lua
-- Faster pattern: call hook.Run once with all players
hook.Add("Tick", "FastNotify", function()
    hook.Run("CustomPlayerLogic", player.GetAll())
end)

-- Slower pattern (for comparison): loop and call hook.Run per player
--[[
hook.Add("Tick", "SlowNotify", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("CustomPlayerLogic", ply)
    end
end)
]]
```
Reason: A single hook.Run with all players avoids repeated hook iteration and function call overhead, making it faster than per-player calls.


```lua
local health = LocalPlayer():Health()
draw.SimpleText(health, "Default", 10, 10)
draw.SimpleText(health, "Default", 10, 30)
draw.SimpleText(health, "Default", 10, 50)
```
Reason: Storing LocalPlayer():Health() in a local variable avoids three redundant function calls per frame.


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

hook.Add("HUDPaint", "FastPaint", function()
    surface.SetDrawColor(white)
    -- draw calls using white
end)
```
Reason: Pre-allocating the Color object once avoids per-frame table creation and is faster.


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


```lua
local ply = LocalPlayer()

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

hook.Add("PlayerSpawn", "CacheLocalPlayerSpawn", function(p)
    if p == LocalPlayer() then
        ply = p
    end
end)
```
Reason: Caching the local player reference in a variable and refreshing it on spawn/init avoids repeated LocalPlayer() calls.


```lua
local function lookingAtEachOther(p1, p2, cosThreshold)
    if not IsValid(p1) or not IsValid(p2) then return false end
    local dir = (p2:GetPos() - p1:GetPos()):GetNormalized()
    local aim1 = p1:GetAimVector()
    local aim2 = p2:GetAimVector()
    return aim1:Dot(dir) > cosThreshold and aim2:Dot(dir) < -cosThreshold
end
```
Reason: Dot product of aim vectors with inter-player direction gives a cheap cosine threshold without math.acos.


```lua
SomeHelper(ply)
```
Reason: Direct call avoids the per-call method/index lookup on the player object, so it is generally faster.


```lua
MsgN("debug line")
```
Reason: MsgN is a C-level function that skips print's Lua-side argument processing and tostring calls, making it faster in hot paths.


```lua
local n = #t
for i = 1, n do
    local v = t[i]
end
```
Reason: Numeric for avoids iterator function overhead from pairs/ipairs and uses direct indexed access, making it fastest for sequential arrays.


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

local players = player.GetAll()
local adminNames = fastFilterMap(players,
    function(p) return IsValid(p) and p:IsAdmin() end,
    function(p) return p:Nick() end
)
```
Reason: Single-pass loop with local functions avoids fn's multiple iterations and closure/curry overhead, improving speed.


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

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

hook.Add("PlayerInitialSpawn", "CachePlayers", refreshPlayerCache)
hook.Add("PlayerDisconnected", "CachePlayers", refreshPlayerCache)

hook.Add("Tick", "ProcessPlayers", function()
    for _, ply in ipairs(cachedPlayers) do
        -- per-tick work on ply
    end
end)
```
Reason: Caching the player list and refreshing only on join/leave avoids calling player.GetAll() every tick, reducing overhead.


```lua
local pdata = {}

-- Write:
local idx = ply:EntIndex()
pdata[idx] = value

-- Read (hot path):
local val = pdata[idx]
```
Reason: Plain Lua table with numeric keys avoids entity metatable/field lookups, making frequent reads faster.


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


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


```lua
local sid = ply:SteamID()
local row = sql.Query("SELECT score FROM players WHERE steamid = " .. sql.SQLStr(sid))
```
Reason: Local SQLite eliminates network latency, making it lower latency than remote MySQL for a single-server setup.


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

local function GetCachedSteamID(ply)
    local id = steamIDCache[ply]
    if id == nil then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```
Reason: Weak-keyed cache avoids repeated native SteamID calls for the same player, speeding up hot paths.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Skips draw.RoundedBox's zero-corner checks and function overhead by using surface primitives directly.


```lua
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("Default")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Single line string")
end)
```
Reason: surface.DrawText is a lower-level call that skips the extra alignment, outline, and wrapper logic in draw.DrawText/draw.SimpleTextOutlined, making it faster for per-frame single-line text.


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


```lua
t = {}
```
Reason: t = {} is O(1) (drops reference for GC) while table.Empty(t) iterates all entries O(n), making it slower for large tables.


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

if set["b"] then
    print("exists")
end
```
Reason: Using a hash set (value as key) gives O(1) lookup instead of O(n) linear scan like table.HasValue.


```lua
local t = { a = 1, b = 2, c = 3 }
```
Reason: Putting fields in the table constructor is faster than assigning after {} because it uses fewer bytecode operations and is optimized by the Lua VM.


```lua
local function randomSeq(t)
    return t[math.random(#t)]
end
```
Reason: Direct indexing with math.random(#t) is O(1) and avoids table.Random's pairs iteration and count overhead.


```lua
x = x * x
```
Reason: Direct multiplication is faster than using the ^ operator or math.pow in Lua.


```lua
for _, ply in pairs(player.GetAll()) do
end
```
Reason: Uses pairs to iterate the table of all connected players from player.GetAll().


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    if IsValid(ent) then
        -- visit the entity
    end
end
```
Reason: ents.FindByClass retrieves only prop_physics entities directly, avoiding construction of a table containing every entity in the map.


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


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: IsValid checks that ent is not NULL and still exists in the world, preventing errors from using removed or invalid entities.


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


```lua
local zeroAng = Angle(0, 0, 0)
local function getZeroAngle()
    zeroAng:Zero()
    return zeroAng
end
```
Reason: Reusing a pre-allocated Angle and resetting it with :Zero() avoids per-call userdata allocation incurred by Angle().


```lua
local color = myaddon.config.color
local read = color
```
Reason: Local variable access avoids repeated nested table lookups, making frequent reads faster than traversing myaddon.config.color each time.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: getDarkRPVar is DarkRP's proper accessor for the job name, avoiding fragile raw NWString calls.


```lua
if (vecA:DistToSqr(vecB) < threshold * threshold) then
    -- within threshold distance
end
```
Reason: DistToSqr avoids the costly square root operation by comparing squared distances, which is optimal for threshold checks.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- visit each entity
end
```
Reason: The GMod wiki recommends using ipairs with ents.GetAll() for efficient array-like iteration over all entities.


```lua
local ply = player.GetByID(1)
local nearby = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: ents.FindInSphere is a faster built-in spatial query than FindInPVS because it only performs a radius distance check without expensive visibility/PVS calculations.


```lua
local function playersInRadius(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 the player list with squared distance is cheaper than ents.FindInSphere plus player filter.


```lua
for i = 1, n do
end
```
Reason: Numeric for loops are optimized by the Lua VM with precomputed bounds, making them faster than equivalent while loops.


```lua
-- Faster pattern: single hook invocation passing all players
hook.Run("TickPlayers", player.GetAll())

-- Slower pattern: loop and invoke hook per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("TickPlayer", ply)
end
```
Reason: A single hook.Run with all players reduces per-call overhead and Lua/C boundary crossings versus looping and calling per player.


```lua
hook.Add("HUDPaint", "FastHealthDraw", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText("Health: " .. hp, "Default", 10, 10)
    draw.SimpleText("HP: " .. hp, "Default", 10, 30)
    draw.SimpleText(tostring(hp), "Default", 10, 50)
end)
```
Reason: Storing the health in a local variable avoids three separate method calls and recomputation within the same frame.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "EfficientPaint", function()
    surface.SetDrawColor(white)
    -- draw operations using white
end)
```
Reason: Pre-allocating the Color object outside the paint hook avoids repeated table creation each frame.


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


```lua
local ply = NULL

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

hook.Add("PlayerSpawn", "CacheLocalPlayerSpawn", function(p)
    if p == LocalPlayer() then ply = p end
end)
```
Reason: Caching the local player in a local variable and updating it via spawn hooks avoids repeated global LocalPlayer() lookups.


```lua
local function playersLookingAtEachOther(a, b)
    local dirA = a:GetAimVector()
    local dirB = b:GetAimVector()
    local toB = (b:EyePos() - a:EyePos()):GetNormalized()
    local cosThresh = 0.5 -- roughly 60 degrees
    return dirA:Dot(toB) > cosThresh and dirB:Dot(toB) < -cosThresh
end
```
Reason: Dot products against the normalized direction between players avoid acos and give a cheap cosine-threshold check for mutual aiming.


```lua
SomeHelper(ply)
```
Reason: SomeHelper(ply) avoids metatable lookup and implicit self dispatch, making it marginally faster and clearer for a helper you control.


```lua
MsgN("debug line")
```
Reason: MsgN is a direct C-bound console write that avoids print's argument formatting and tostring overhead.


```lua
for i = 1, #arr do
    local v = arr[i]
end
```
Reason: Numeric for is fastest because it avoids iterator overhead and benefits from LuaJIT optimization on sequential indexing.


```lua
local function filterMap(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 pipeline equivalent to fn.Map(fn.Filter(tbl, pred), map)
local nums = {1,2,3,4,5,6}
local squaresOfEvens = filterMap(nums, function(x) return x % 2 == 0 end, function(x) return x * x end)
```
Reason: Single-pass loop with locals avoids fn's intermediate tables and combinator call overhead, making it faster.