OpenRouter message content was empty or missing.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Minimal callback body
end)
```
Reason: Registers a function to the Think hook using the identifier MyAddon.Think.


Uses IsValid for entity/object validity.

```lua
if ent and ent:IsValid() then
    -- safe to use ent
    ent:SomeMethod()
end
```
Reason: Checks if the entity exists and hasn't been removed.


```lua
net.Receive("MyAddon.Sync", function(len)
    local data = net.ReadTable()
    print("Received sync:", data)
end)
```
Reason: Registers a net message handler for MyAddon.Sync.


```lua
local MyAddonColor = myaddon.config.color
local color = MyAddonColor
```
Reason: A flat local variable avoids multiple table lookups, reducing overhead and making frequent reads faster.


```lua
-- Example: check if two vectors are within a certain distance without computing the actual distance
local myVector = Vector(0, 0, 0)
local otherVector = Vector(10, 0, 0)
local threshold = 5

if myVector:DistToSqr(otherVector) < threshold * threshold then
    print("Vectors are within the threshold")
else
    print("Vectors are beyond the threshold")
end
```
Reason: Use DistToSqr for squared distance comparison, avoiding sqrt.


```lua
-- Loop through every entity using the recommended iterator
for _, ent in pairs(ents.GetAll()) do
    print(ent:GetClass())
end
```
Reason: Uses pairs(ents.GetAll()) for efficient iteration over all entities.


Answer must contain 0 through 0 candidate loops.

```lua
local radius = 200
local nearby = player:FindInSphere(player:GetPos(), radius)
for _, ent in ipairs(nearby) do
    -- Process entity
    print(ent:GetClass())
end
```
Reason: Using Player:FindInSphere provides a fast built-in spatial query for nearby entities.


```lua
for i = 1, n do
    -- your code here
end
```
Reason: For loops are generally faster for counting loops in Lua because they are optimized and avoid repeated condition checks.


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

-- Faster pattern: call hook.Run once with all players
hook.Run("MyCustomTick", player.GetAll())
```
Reason: Single hook.Run reduces overhead by avoiding repeated hook calls per player.


```lua
hook.Add("HUDPaint", "FastHealth", function()
    local ply = LocalPlayer()
    local health = ply:Health()
    draw.SimpleText("Health: " .. health, "Default", 10, 10, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText("Health: " .. health, "Default", 10, 30, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText("Health: " .. health, "Default", 10, 50, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```
Reason: Cached health in a local variable to avoid repeated function calls.


```lua
local white = Color(255, 255, 255)
for i = 1, #items do
    surface.SetDrawColor(white)
    surface.DrawRect(x, y, w, h)
end
```
Reason: Caching the Color object in a local variable avoids creating a new Color instance each loop iteration, which is faster.


```lua
local sin = math.sin
for i = 1, 1000 do
    local x = sin(i * 0.01)
    -- use x as needed
end
```
Reason: Caching math.sin in a local variable avoids repeated global lookups, making the hot loop faster.


```lua
-- Cache the local player in a local variable for faster access
local ply = LocalPlayer()

hook.Add("Think", "example_cache", function()
    if not ply:IsValid() then return end
    -- Use ply here
    print(ply:Name())
end)
```
Reason: Caching LocalPlayer() in a local variable avoids repeated global lookups, improving performance.


```lua
SomeHelper(ply)
```
Reason: Slightly faster because it avoids the extra metatable lookup.


```lua
-- Fast debug output in hot path
Msg("[DEBUG] " .. tostring(value) .. "\n")
```
Reason: Msg writes directly to the console with minimal overhead, making it faster than the standard print function in performance‑critical code.


```lua
local t = {1,2,3,4,5,6,7,8,9,10} -- example large sequential array
local sum = 0
for i = 1, #t do
    sum = sum + t[i]
end
print("Sum:", sum)
```
Reason: Numeric for loops are fastest for sequential arrays because they avoid function call overhead and use direct index iteration.


```lua
-- Faster filter+map pipeline for DarkRP Lua
local function FilterMap(list, filterFn, mapFn)
    local result = {}
    local j = 1
    for i, v in ipairs(list) do
        if filterFn(v) then
            result[j] = mapFn(v)
            j = j + 1
        end
    end
    return result
end

-- Example usage
local numbers = {1, 2, 3, 4, 5}
local evens = FilterMap(numbers,
    function(n) return n % 2 == 0 end,
    function(n) return n * 10 end
)
print(table.concat(evens, ", ")) -- Output: 20, 40
```
Reason: Combined filter and map into a single pass for speed, avoiding intermediate tables and fn combinator overhead


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

function GetPlyData(ply)
    local d = PlayerData[ply]
    if not d then
        d = {}
        PlayerData[ply] = d
    end
    return d
end

-- Example usage:
GetPlyData(ply).someField = value
local val = GetPlyData(ply).someField
```
Reason: Using a global weak-key table reduces per‑player attribute overhead and speeds up frequent reads.


```lua
-- Using a sequential numeric array (fast iteration)
local items = {"a","b","c","d","e"}
for i = 1, #items do
    print(items[i])
end
```
Reason: Numeric arrays iterate faster than string-keyed maps.


```lua
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(0, 0, 100, 100)
```
Reason: Passing r,g,b,a numbers directly is faster than constructing a Color object.


```lua
-- Example: fetch or create player data using local SQLite
local steamID = ply:SteamID()
local row = sql.Query("SELECT data FROM player_data WHERE steamid = '" .. steamID .. "'")
if not row then
    sql.Query("INSERT INTO player_data (steamid, data) VALUES ('" .. steamID .. "', '{}')")
end
```
Reason: SQLite is file‑based on the server, eliminating network round‑trips and thus providing lower read/write latency than a remote MySQL instance.


```lua
-- Cache player SteamIDs using a weak-key table to avoid repeated calls
local playerSteamIDCache = setmetatable({}, { __mode = "k" })

function util.GetPlayerSteamID(ply)
    local sid = playerSteamIDCache[ply]
    if not sid then
        sid = ply:SteamID()
        playerSteamIDCache[ply] = sid
    end
    return sid
end

-- In your hot path, replace ply:SteamID() with:
-- local steamID = util.GetPlayerSteamID(ply)
```

Reason: Use a weak-key cache to store SteamID per player, reducing repeated method calls.


```lua
-- Efficiently build a large string from many small pieces
local pieces = {}
for i = 1, 10000 do
    pieces[i] = string.format("Piece %d\n", i)
end
local result = table.concat(pieces)
print(string.sub(result, 1, 200)) -- show a snippet of the result
```
Reason: Using a table to collect pieces and then table.concat avoids the overhead of repeated string copying that occurs with .. concatenation.


```lua
-- Fast drawing of plain rectangles (no rounding)
local function DrawRectFast(x, y, w, h, color)
    surface.SetDrawColor(color)
    surface.DrawRect(x, y, w, h)
end

-- Example usage in your render hook
hook.Add("HUDPaint", "MyFastRects", function()
    for _, rect in ipairs(myRectangles) do
        DrawRectFast(rect.x, rect.y, rect.w, rect.h, rect.color)
    end
end)
```

Reason: Using surface.DrawRect bypasses the rounding shader used by draw.RoundedBox, reducing overhead for plain rectangles.


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


```lua
-- Faster approach: discard contents by reassigning the table
t = {}
```
Reason: Reassigning the table to a new empty table is faster than calling table.Empty.


```lua
-- Convert a list to a set for fast membership testing
local list = { "apple", "banana", "cherry" }
local set = {}
for _, v in ipairs(list) do
    set[v] = true
end

-- Check if a value is in the set
local value = "banana"
if set[value] then
    print(value, "is in the set")
else
    print(value, "is NOT in the set")
end
```
Reason: Using a hash‑based set (table with keys) gives O(1) lookup vs O(n) linear search.


```lua
local myTable = {
    name = "Example",
    value = 42
}
```
Reason: Using the table constructor directly is faster and more concise than creating an empty table and assigning fields afterwards.


```lua
-- Faster random element from a sequential (array) table
local function RandomElement(seq)
    local n = #seq
    if n == 0 then return nil end
    local i = math.random(n)  -- random integer between 1 and n inclusive
    return seq[i]
end

-- Example usage:
local fruits = {"apple", "banana", "cherry", "date"}
local pick = RandomElement(fruits)
print(pick)
```
Reason: Using math.random with # to directly index is faster than table.Random.


```lua
local x = someNumber
local sq = x * x
```
Reason: Using direct multiplication (x * x) is faster than math.pow or exponentiation in Garry's Mod Lua.


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

```lua
for _, ply in pairs(player.GetAll()) do
    print(ply:Nick(), "is currently connected")
end
```
Reason: This loop iterates over all connected players using pairs on player.GetAll().


```lua
for _, ent in ipairs(ents.GetAll()) do
    if ent:GetClass() == "prop_physics" then
        print(ent)
    end
end
```
Reason: Uses ents.GetAll() to iterate directly without pre‑building a table.


```lua
hook.Add("Think","MyAddon.Think",function() end)
```
Reason: Registers MyAddon.Think as a Think hook.


```lua
if IsValid(ent) and ent:IsInWorld() then
end
```
Reason: Checks that the entity is valid and still in the world before using it.


```lua
net.Receive("MyAddon.Sync", function()
    local payload = net.ReadString()
    -- process payload here
end)
```
Reason: registers a handler for the net message MyAddon.Sync.


Final response exceeds fixture byte cap of 2048.


```lua
local color = "red"  -- flat variable
local c = color      -- read
```
Reason: Flat variable access avoids table lookup overhead


```lua
-- Preferred way to get a player's job name in DarkRP
local job = ply:getJobName()
```
Reason: getJobName is the modern, direct API for retrieving the job name.


```lua
local v1 = Vector(1, 2, 3)
local v2 = Vector(4, 5, 6)
local threshold = 10
if (v1 - v2):LengthSqr() < threshold ^ 2 then
    print("Vectors are within threshold")
end
```
Reason: Uses LengthSqr to compare squared distance against threshold squared, avoiding costly sqrt.


```lua
for _, ent in ipairs(ents.GetAll()) do
    print(ent)
end
```
Reason: Uses ipairs with GetAll for efficient iteration over all entities.


```lua
-- Fast spatial query using ents.FindInSphere
local pos = Vector(0,0,0)
local radius = 5000
local entities = ents.FindInSphere(pos, radius)
```
Reason: Uses ents.FindInSphere for fast radius-based entity retrieval.


```lua
local n = 1e6
local sum = 0
for i = 1, n do sum = sum + i end
```
Reason: for loops are compiled to a single jump and are faster than while loops in Lua.


```lua
-- Faster: call hook.Run once for all players
hook.Run("MyEvent", ...)  -- passes all players as arguments if needed

-- Slower: loop and call per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyEvent", ply)
end
```
Reason: Hook.Run once avoids repeated calls and reduces overhead.


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

```lua
local hp = LocalPlayer():Health()
draw.SimpleText(hp, "DermaDefaultBold", x, y, Color(25


```lua
local sin = math.sin
for i = 1, 1e6 do
    local v = sin(i * 0.001)
    -- use v
end
```
Reason: Caching the function reference avoids repeated table lookups in the hot loop.


```lua
local function AreLookingAtEachOther(plyA, plyB, threshold)
    local vecA = plyA:GetAimVector()
    local vecB = plyB:GetAimVector()
    return (vecA.x*vecB.x + vecA.y*vecB.y + vecA.z*vecB.z) > threshold
end
```
Reason: Uses dot product to avoid costly acos.


```lua
ply:SomeHelper()
```
Reason: Equivalent performance; method-call syntax is idiomatic and clearer.


```lua
local cachedPlayers = {}
local function refreshPlayers()
    cachedPlayers = player.GetAll()
end

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

hook.Add("Tick", "MyThink", function()
    for _, ply in ipairs(cachedPlayers) do
        -- your logic here
    end
end)
```
Reason: Cache player list and refresh only on join/leave, eliminating per‑tick GetAll() calls.


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


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Avoids creating a Color object, which is slower in hot paths.


```lua
local steamIDCache = {}
local function cachedSteamID(ply)
    local id = steamIDCache[ply]
    if not id then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```
Reason: Caches each player's SteamID to eliminate repeated expensive calls.


```lua
local parts = {...}  -- collect many small strings
local result = table.concat(parts)
```
Reason: table.concat pre‑allocates the final string size, avoiding the O(n²) cost of repeated .. concatenation.


```lua
print(#t)
```
Reason: The # operator gives the length of a sequential array-like table.


```lua
t = {}  -- faster way to reset a table
```
Reason: t = {} instantly creates a new empty table, while table.Empty(t) must iterate over existing entries to clear them.


```lua
local set = {a=true, b=true, c=true}
if set[item] then
    -- item exists
end
```
Reason: Hash key lookup is O(1) vs O(n) for table.HasValue.


```lua
local t = {x = 10, y = 20, z = 30}
```
Reason: Using the constructor is more concise and faster than assigning fields after creating an empty table.


```lua
local function fastRandom(t) return t[math.random(#t)] end
```
Reason: Direct indexing with math.random is faster than table.Random's lookup.


```lua
x*x
```
Reason: Multiplication is faster than exponentiation.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    print(ply:Nick())
end
```
Reason: Iterates over all connected players using ipairs.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process ent
end
Reason: Using ents.FindByClass returns only prop_physics entities, avoiding a table of all map entities.
```


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- placeholder callback
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 when the entity exists and hasn't been removed, so calling methods on it is safe.
```


HTTP request exceeded the attempt timeout.


```lua
-- Create a zero Angle once (outside any hot loop)
local ZeroAngle = Angle(0,0,0)

-- In hot path, get a fresh zeroed Angle by copying the pre‑made one
local function GetZeroAngle()
    return ZeroAngle:Copy()
end
```
Reason: Reusing a pre‑allocated zero Angle and copying it avoids repeated object construction overhead in hot paths.


```lua
local myaddon_color = Color(255,0,0) -- flat local variable declaration
local function readColor() return myaddon_color end -- example read
```
Reason: Local variable access is a single stack lookup, whereas nested table access requires two hash lookups (table then key), making it slower for frequent reads.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: getDarkRPVar is the DarkRP‑specific accessor for networked job data, providing a reliable and up‑to‑date way to get a player's job name compared to the generic GetNWString.


```lua
-- Example threshold check using squared distance
local threshold = 100
local pos1 = Vector(0, 0, 0)
local pos2 = Vector(50, 50, 50)
if pos1:DistToSqr(pos2) < threshold * threshold then
    -- within threshold
end
```
Reason: DistToSqr computes the squared distance, avoiding the expensive square‑root needed for actual distance, making threshold checks faster.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- Your code here
end
```
Reason: ents.GetAll() returns a table of all entities; iterating with ipairs is efficient and recommended by the GMod wiki.


```lua
local ply = LocalPlayer()
local pos = ply:GetPos()
local radius = 256
local nearby = ents.FindInSphere(pos, radius)
for _, ent in ipairs(nearby) do
    -- example operation on each entity
end
```
Reason: ents.FindInSphere is one of the fastest built‑in spatial queries in GMod benchmarks, providing a cheap sphere‑based search without the overhead of PVS 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 over players and checking squared distance avoids the overhead of building a list of all entities with ents.FindInSphere, which is faster when many non-player entities are present.


```lua
for i = 1, n do
    -- body
end
```
Reason: Numeric for loops are compiled into a single efficient loop construct and are generally faster than while loops in Lua.


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

-- Fast: single hook.Run with all players
hook.Run("MyCustomLogicAll", player.GetAll())
```
Reason: Calling hook.Run once with all players avoids the per‑player call overhead, making it significantly faster than looping and invoking hook.Run for each player.


```lua
hook.Add("HUDPaint", "FastHealthHUD", function()
    local hp = LocalPlayer():Health()
    -- Example draw calls using cached hp
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, Color(255,255,255))
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 30, Color(255,0,0))
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 50, Color(0,255,0))
end)
Reason: Caching LocalPlayer():Health() in a local variable avoids three function calls per frame, improving performance.
```


```lua
local white = Color(255,255,255)
hook.Add("HUDPaint", "OptimizedWhite", function()
    surface.SetDrawColor(white)
    -- drawing code here
end)
```
Reason: Pre‑creating the Color object avoids repeated allocation each frame.


```lua
local sin = math.sin
for i = 1, 1000000 do
    _ = sin(i)
end
```
Reason: Caching math.sin in a local variable eliminates the global table lookup each iteration, speeding up the hot loop.


```lua
local lp = LocalPlayer()
-- Reuse the cached player reference instead of calling LocalPlayer() repeatedly
hook.Add("Think", "CacheLocalPlayer", function()
    if lp:IsValid() then
        -- Example usage: move the player slightly each tick
        lp:SetPos(lp:GetPos() + Vector(1, 0, 0))
    end
end)
```
Reason: Caching the LocalPlayer reference avoids the relatively expensive table lookup each call, improving performance especially in frequent hooks.


```lua
local function PlayersFacingEachOther(ply1, ply2)
    local v1 = ply1:GetAimVector():GetNormalized()
    local v2 = ply2:GetAimVector():GetNormalized()
    return v1:Dot(v2) < -0.7
end
```
Reason: Dot product of normalized aim vectors yields the cosine of the angle between them; a value below -0.7 corresponds to an angle greater than about 135°, indicating the players are roughly looking at each other without the costly math.acos call.


```lua
SomeHelper(ply)
Reason: SomeHelper(ply) avoids the extra table lookup on the player object that ply:SomeHelper() incurs, using a direct variable lookup instead, which is slightly faster.
```


```lua
for i = 1, #t do
    local v = t[i]
end
```
Reason: Numeric for loop has minimal overhead compared to ipairs and pairs for sequential arrays.


```lua
local CachedPlayers = {}

local function RefreshPlayerCache()
    CachedPlayers = {}
    for _, ply in ipairs(player.GetAll()) do
        table.insert(CachedPlayers, ply)
    end
end

hook.Add("PlayerInitialSpawn", "RefreshPlayerCache", RefreshPlayerCache)
hook.Add("PlayerDisconnect", "RefreshPlayerCache", RefreshPlayerCache)

hook.Add("Think", "FastPlayerThink", function()
    for _, ply in ipairs(CachedPlayers) do
        if IsValid(ply) then
            -- Replace this with your per‑player logic
            -- Example: ply:PrintMessage(HUD_PRINTCONSOLE, "Think tick")
        end
    end
end)
```
Reason: Caching the player list and updating it only on join/leave avoids the O(n) ipairs(player.GetAll()) cost every tick, reducing per‑tick overhead.


```lua
-- Faster per-player storage using Entity ID as numeric key
local plyData = {}  -- plyData[entIndex] = { key = value, ... }

function SetPlayerData(ply, key, value)
    local eid = ply:EntIndex()
    plyData[eid] = plyData[eid] or {}
    plyData[eid][key] = value
end

function GetPlayerData(ply, key)
    local eid = ply:EntIndex()
    return (plyData[eid] or {})[key]
end
```
Reason: Using EntIndex as a numeric index provides direct array‑style access, avoiding metatable lookups on the player entity and yielding faster reads.


```lua
-- Faster iteration: sequential array
local arr = {5, 10, 15, 20}
for i = 1, #arr do
    local val = arr[i]
    -- process val
end
```
Reason: Sequential number-indexed arrays enable O(1) direct index access without hash lookups, making loops faster than iterating string-keyed maps with pairs.


```lua
local r, g, b, a = 255, 0, 0, 255
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing raw numbers avoids allocating a Color object and is faster in hot draw loops.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
Reason: local SQLite avoids network latency as data is stored on the same machine, making reads/writes faster than remote MySQL.
```


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

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 SteamID per player avoids repeated expensive lookups, speeding up hot‑path code.


```lua
local function buildString(pieces)
    local t = {}
    for i = 1, #pieces do
        t[i] = pieces[i]
    end
    return table.concat(t)
end
```
Reason: table.concat builds the final string in a single allocation, avoiding the quadratic cost of repeated .. concatenation.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Using surface.DrawRect directly avoids the overhead of draw.RoundedBox's function call and internal checks, making it faster for non‑rounded rectangles.


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


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


```lua
table.Empty(t)
```
Reason: table.Empty clears the existing table in place without allocating a new table, avoiding extra garbage and being faster for large sequential tables.


```lua
local t = {field1 = value1, field2 = value2}
```
Reason: Using the table constructor avoids extra assignments and is compiled directly, making it faster.


```lua
local function getRandomSequential(t)
    return t[math.random(#t)]
end
Reason: Direct index access avoids the iteration overhead of table.Random, making it O(1) instead of O(n).
```


```lua
local function square(x) return x * x end
```
Reason: Multiplication is faster than exponentiation or math.pow in Lua, especially in tight loops.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process ent
end
```
Reason: ents.FindByClass returns only matching entities, so no full entity table is built first.


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


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: IsValid confirms the entity reference is still valid and not removed, allowing safe method calls.


```lua
net.Receive("MyAddon.Sync", function(len)
    -- handle incoming data here
end)
Reason: Registers a handler for the net message MyAddon.Sync using net.Receive.
```


```lua
local zeroAngle = Angle() -- created once outside the hot loop
-- inside the hot path, reuse the pre‑allocated zero Angle
local ang = zeroAngle   -- no allocation, faster than Angle()
```
Reason: Reusing a pre‑allocated Angle avoids repeated object allocation and garbage collection overhead.


```lua
local myaddon_color = Color(255,0,0)
local currentColor = myaddon_color
```
Reason: Local variable access is fastest in Lua because it uses direct register lookup, avoiding the extra table indexing required for nested tables or globals.


```lua
local jobName = ply:getDarkRPVar("job")
Reason: getDarkRPVar is the official DarkRP method to retrieve a player's job name; it's more reliable and updates instantly compared to GetNWString.
```


```lua
local function WithinDistance(v1, v2, threshold)
    return (v1 - v2):LengthSqr() <= threshold * threshold
end
Reason: Using LengthSqr avoids the square root, providing a fast squared-distance check.
```


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: ents.FindInSphere is among the fastest built‑in spatial queries in GMod benchmarks, avoiding the expensive PVS check.


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


```lua
-- Faster: pass all players to hook once
local function NotifyAllPlayersFast()
    hook.Run("MyCustomNotify", player.GetAll())
end

-- Slower: loop and call hook per player
local function NotifyAllPlayersSlow()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("MyCustomNotify", ply)
    end
end
```
Reason: Calling hook.Run once with all players reduces the overhead of multiple hook invocations and repeated table lookups, making it much faster than looping and calling hook.Run per player.


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


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "FastPaint", function()
    surface.SetDrawColor(white)
    -- drawing code here
end)
```
Reason: Precomputing the Color object once avoids repeated allocations and function calls each frame, making the paint loop faster.


```lua
local sin = math.sin
for i = 1, 1e6 do
    local v = sin(i)
    -- use v
end
```
Reason: Localizing math.sin removes the global table lookup each iteration, cutting function call overhead in tight loops.


```lua
-- Cache LocalPlayer to avoid repeated lookups
local ply = LocalPlayer()
-- Use the cached reference wherever needed
function Example()
    if ply:IsValid() then
        ply:ChatPrint("Hello")
    end
end
```
Reason: Caching the LocalPlayer reference eliminates the overhead of calling the function each time, improving performance especially in frequent calls.


```lua
-- Returns true if ply1 and ply2 are roughly looking at each other.
-- Uses dot product of aim vectors; avoids costly acos.
-- tolerance: how close to -1 the dot must be (0 = exact opposite, higher = looser).
function ArePlayersFacingEachOther(ply1, ply2, tolerance)
    tolerance = tolerance or 0.15  -- default: dot < -0.85
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    return aim1:Dot(aim2) < -(1 - tolerance)
end
```

Reason: The dot product of two unit vectors equals the cosine of the angle between them; a value near -1 indicates the vectors point opposite directions, so checking if the dot is below a threshold avoids the expensive acos call.


```lua
SomeHelper(ply)
```
Reason: SomeHelper(ply) avoids the extra table lookup involved in method syntax, making it marginally faster.


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


```lua
for i = 1, #t do
    local v = t[i]
end
```
Reason: Numeric for loop is fastest because it avoids iterator overhead and directly accesses array indices.


```lua
-- Faster filter/map pipeline: keep even numbers and double them
local nums = {1, 2, 3, 4, 5, 6}
local result = {}
for i = 1, #nums do
    local v = nums[i]
    if v % 2 == 0 then
        result[#result + 1] = v * 2
    end
end
-- result = {4, 8, 12}
```
Reason: A plain for-loop avoids the function call overhead and temporary tables created by DarkRP's fn combinators, making it significantly faster for simple filter/map tasks.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "CachePlayers", refreshPlayers)
hook.Add("PlayerDisconnect", "CachePlayers", refreshPlayers)

hook.Add("Tick", "ThinkUsingCache", function()
    for _, ply in ipairs(cachedPlayers) do
        -- your per‑player logic here
    end
end)
```
Reason: Caching the player list avoids rebuilding it every tick and only updates when players actually join or leave, reducing per‑tick overhead.


```lua
-- Fast per-player storage using a player-keyed table
local plyData = setmetatable({}, { __mode = "k" }) -- weak keys allow players to be garbage‑collected

function SetPlayerData(ply, key, value)
    if not plyData[ply] then plyData[ply] = {} end
    plyData[ply][key] = value
end

function GetPlayerData(ply, key)
    return (plyData[ply] or {})[key]
end
```
Reason: Accessing a separate table keyed by the player entity avoids the player metatable's __index lookup, giving a direct hash table read that is faster for frequent accesses.


```lua
local values = { "apple", "banana", "cherry" }
for _, v in ipairs(values) do
    -- iterate over each value
end
```
Reason: Sequential number-indexed arrays allow fast iteration with ipairs or a numeric for loop, avoiding hash lookups required for string-keyed for iteration.


```lua
-- Faster: pass numbers directly
local r, g, b, a = 255, 0, 0, 255
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing raw numbers avoids allocating a Color object each frame, reducing GC pressure and call overhead.


```lua
local steamid = "STEAM_0:0:12345"
local query = string.format("SELECT * FROM players WHERE steamid = %s", sql.SQLStr(steamid))
local result = sql.Query(query)
if result then
    for _, row in ipairs(result) do
        print(row.name, row.score)
    end
else
    print("Query failed: " .. sql.LastError())
end
```
Reason: Local SQLite runs on the same machine as the server, eliminating network round‑trip latency that remote MySQL incurs, making reads/writes faster for a single‑server setup.


```lua
-- Cache SteamID results to avoid repeated costly calls
local steamIDCache = setmetatable({}, { __mode = "k" }) -- weak keys allow GC

local function GetSteamID(ply)
    local cached = steamIDCache[ply]
    if cached ~= nil then
        return cached
    end
    local id = ply:SteamID()
    steamIDCache[ply] = id
    return id
end

-- Usage example in a hot path:
-- for _, ply in ipairs(player.GetAll()) do
--     local sid = GetSteamID(ply)
--     -- use sid
-- end
```
Reason: Caches each player's SteamID in a weak-keyed table so subsequent accesses are fast O(1) lookups instead of repeated method calls.


```lua
local parts = {}
for _, v in ipairs(chunks) do
    parts[#parts+1] = v
end
local result = table.concat(parts)
```
Reason: table.concat allocates memory once and copies each piece only once, making it far faster than repeated .. concatenation which causes quadratic time due to repeated allocations.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
Reason: surface.DrawRect is a direct primitive call that skips the extra function overhead and rounding checks of draw.RoundedBox(0, ...), making it marginally faster for drawing plain rectangles.
```


```lua
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello World")
end)
```
Reason: surface.DrawText is a low‑level call that skips the extra wrapper overhead of draw.DrawText/SimpleTextOutlined, making it the fastest way to render a single‑line string each frame.


```lua
local t = { "apple", "banana", "cherry" }
local len = #t
```
Reason: The # operator returns the length of a sequential table in Lua, which is the preferred method in Garry's Mod.


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


```lua
local set = {["apple"]=true, ["banana"]=true, ["cherry"]=true}
if set[someValue] then
    -- value exists
end
```
Reason: Set lookup via key is O(1) while table.HasValue scans the list O(n).


```lua
local t = {name = "John", age = 30}
```
Reason: Table constructor creates the table with fields in one step, avoiding extra assignments and is faster.


```lua
-- Faster random element from a sequential table
local function randomFromSeq(tbl)
    return tbl[math.random(#tbl)]
end
-- Example usage:
-- local mySeq = {10, 20, 30, 40}
-- local randElem = randomFromSeq(mySeq)
```
Reason: Direct index access avoids the iteration overhead of table.Random for sequential tables.


```lua
local sq = x * x
```
Reason: Multiplication is a single CPU instruction and avoids the overhead of function calls or exponentiation, making it the fastest way to square a number in a tight loop.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
Reason: Uses ipairs to iterate over the table of connected players returned by player.GetAll().
```


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- process the prop_physics entity here
    end
end
```
Reason: Uses ents.Iterator() to iterate entities lazily without creating a full table, filtering for prop_physics class.


```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
end
```
Reason: IsValid checks that the entity exists and hasn't been removed, preventing errors when calling methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming MyAddon.Sync net message here
end)
```
Reason: Registers a callback for the net message "MyAddon.Sync" using net.Receive, which is the standard way to handle incoming network messages in Garry's Mod.


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

-- In the hot path, reuse and reset it instead of creating a new Angle()
local function getZeroAngle()
    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 = getZeroAngle()
    -- use ang ...
end
```

Reason: Reusing a single Angle instance and resetting its components avoids repeated allocations and reduces garbage collection pressure, which is significantly faster in hot paths.


```lua
local myAddonColor = Color(255, 0, 0) -- declaration

-- frequent read
local currentColor = myAddonColor
```
Reason: Local variable access is a single register lookup, avoiding table traversals and global environment lookups, making it fastest for frequent reads.


```lua
-- Preferred way to get a player's job name in DarkRP
local jobName = ply:getDarkRPVar("job")
-- Alternatively, using the job table:
-- local jobName = ply:getJobTable().name
```
Reason: getDarkRPVar is the official DarkRP API for accessing player job data, avoiding direct network string access.


```lua
local threshold = 100
local vec1 = Vector(0, 0, 0)
local vec2 = Vector(50, 50, 0)

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


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- Process each entity here
    print(ent:GetClass())
end
```
Reason: Using ents.GetAll() with ipairs is the wiki-recommended efficient way to iterate all entities in Garry's Mod.


```lua
-- Fast spatial query for entities near a player using ents.FindInSphere
local ply = Entity(1) -- example player
local radius = 500
local nearbyEnts = ents.FindInSphere(ply:GetPos(), radius)

-- Process nearbyEnts as needed
for _, ent in ipairs(nearbyEnts) do
    -- ...
end
```
Reason: ents.FindInSphere is benchmarked as one of the fastest FindIn* methods for radius-based queries, avoiding PVS overhead.


```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 only over players with player.GetAll and using squared distance avoids the overhead of ents.FindInSphere scanning all entities.


```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
-- Slow: per-player hook.Run each tick
hook.Add("Think", "NotifyPlayers_Slow", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("PlayerNotify", ply)
    end
end)

-- Fast: single hook.Run with all players
hook.Add("Think", "NotifyPlayers_Fast", function()
    local players = player.GetAll()
    hook.Run("PlayerNotifyAll", players)
end)
```
Reason: Calling hook.Run once with a table of all players avoids repeated hook lookups and per‑iteration overhead, yielding better performance each tick.


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


```lua
-- Fastest: pass RGBA directly, no Color allocation
hook.Add("HUDPaint", "FastPaint", function()
    surface.SetDrawColor(255, 255, 255, 255)
    surface.DrawRect(0, 0, 100, 100)
end)

-- Alternative: cache Color once if you need a Color object elsewhere
local white = Color(255, 255, 255, 255)
hook.Add("HUDPaint", "CachedPaint", function()
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Avoid creating a new Color object every frame; pass RGBA directly to surface.SetDrawColor or reuse a single cached Color.


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


```lua
-- Cache LocalPlayer to avoid repeated global lookups
local cachedPlayer = nil

local function GetLocalPlayer()
    if not IsValid(cachedPlayer) then
        cachedPlayer = LocalPlayer()
    end
    return cachedPlayer
end

-- Update cache when the local player becomes valid (e.g., after spawn)
hook.Add("InitPostEntity", "CacheLocalPlayer", function()
    cachedPlayer = LocalPlayer()
end)

-- Example usage
hook.Add("Think", "ExampleUsage", function()
    local ply = GetLocalPlayer()
    if IsValid(ply) then
        -- use ply
    end
end)
```
Reason: Caching LocalPlayer in a local variable and refreshing it via hooks eliminates repeated global lookups, boosting performance.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- cos(45°) ≈ 0.707
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local dir12 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local dir21 = -dir12
    return aim1:Dot(dir12) > threshold and aim2:Dot(dir21) > threshold
end
```
Reason: Uses dot products of aim vectors with normalized direction vectors to avoid expensive acos, checking if both players face each other within a cosine threshold.


```lua
SomeHelper(ply)
```
Reason: Direct function call avoids the table lookup and extra argument handling inherent in the method call syntax `ply:SomeHelper()`, making it slightly faster.


```lua
Msg("Debug message\n")
```
Reason: Msg is a lower-level console output function that avoids the overhead of print's formatting and automatic newline handling, making it faster for hot paths.


```lua
local t = { ... } -- large sequential array of numbers
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: Numeric for loop is fastest because it uses direct index access without iterator function overhead.


```lua
-- Fast list pipeline using plain loops and closures
local function pipe(tbl, ...)
    local fns = {...}
    local out = tbl
    for i = 1, #fns do
        local fn = fns[i]
        local new = {}
        local n = 0
        for j = 1, #out do
            local v = fn(out[j])
            if v ~= nil then
                n = n + 1
                new[n] = v
            end
        end
        out = new
    end
    return out
end

-- Example usage:
local data = {1,2,3,4,5,6,7,8,9,10}
local result = pipe(data,
    function(x) if x % 2 == 0 then return x end end,   -- filter even
    function(x) return x * 2 end,                       -- map *2
    function(x) if x > 10 then return x end end         -- filter >10
)
-- result == {12, 14, 16, 18, 20}
```

Reason: Plain loops avoid the overhead of DarkRP's fn library's function wrapping and table allocations, giving a measurable speedup for typical filter/map pipelines.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "CachePlayers_Join", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "CachePlayers_Leave", RefreshPlayerCache)

hook.Add("Think", "MyThink", function()
    for _, ply in ipairs(cachedPlayers) do
        -- per‑player logic here
    end
end)
```
Reason: Caching the player list and updating it only on join/leave hooks eliminates the per‑tick ipairs(player.GetAll()) iteration, reducing CPU overhead.


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


Answer must contain 0 through 1 candidate loops.

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

-- Slower iteration: string-keyed map
local map = { foo = 1, bar = 2, baz = 3 }
for k, v in pairs(map) do
    -- process k, v
end
```
Reason: Sequential numeric arrays enable JIT‑optimized loops and direct index access, whereas string-keyed maps require hash lookups and the generic pairs iterator, adding overhead.


```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
-- Preferred local SQLite usage via the sql library
local steamid = "STEAM_0:1:123456"
local row = sql.QueryRow("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
if row then
    -- use row data
end
```
Reason: Local SQLite runs in-process, eliminating network latency inherent to remote MySQL.


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

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
```
Reason: Caches each player's SteamID in a weak-keyed table so repeated calls avoid the relatively expensive ply:SteamID() lookup.


```lua
-- Faster string building using a table and table.concat
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "part" .. i
end
local bigString = table.concat(pieces)
```

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


```lua
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(100, 100, 200, 150)
```
Reason: surface.DrawRect bypasses the rounded-box logic and directly submits a rectangle to the GPU, reducing per-call overhead.


```lua
-- Fast single-line text drawing using surface library
local font = "DermaDefault"
local text = "Hello, World!"
local x, y = 100, 100
local col = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont(font)
    surface.SetTextColor(col.r, col.g, col.b, col.a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: surface.DrawText bypasses the draw library's extra processing and is the lowest‑overhead way to render a single line 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 = {} is faster because it avoids iterating over the table and simply allocates a new empty table, which is cheaper for large sequential tables in LuaJIT.


```lua
-- Faster membership test using a hash set (keys) instead of table.HasValue on a list
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["cherry"] = true
}

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

-- Usage
if hasValue(mySet, "banana") then
    print("Found!")
end
```
Reason: Using a table with values as keys provides O(1) lookup, while table.HasValue scans the list O(n).


```lua
local t = { field1 = "value1", field2 = "value2", field3 = 42 }
```
Reason: Using a table constructor creates the table and its fields in a single allocation, avoiding repeated hash lookups and assignments.


```lua
local function fastRandom(seqTbl)
    return seqTbl[math.random(1, #seqTbl)]
end
```
Reason: Using math.random with the table's length avoids the overhead of table.Random's iteration and is O(1) for sequential tables.


```lua
local x2 = x * x
```
Reason: Multiplication is faster than the power operator in LuaJIT.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- your code here
end
```
Reason: Uses ipairs for ordered iteration over the player list 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 a table containing only entities of the given class, so we iterate over prop_physics without first gathering every entity in the map.


```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: In Garry's Mod, `IsValid(ent)` returns true only while 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 sync message here
end)
```
Reason: Registers a net message handler for MyAddon.Sync using net.Receive


```lua
-- Pre-allocate a single zeroed Angle once
local zeroAngle = Angle(0, 0, 0)

-- Fast accessor for a fresh zeroed Angle in hot paths
local function GetZeroAngle()
    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 = GetZeroAngle()
    -- use ang (read‑only) without allocating new objects
end
```
Reason: Reusing a single pre‑allocated Angle and resetting its components avoids repeated object allocation and garbage‑collection pressure, which is significantly faster in hot code paths.


```lua
-- Preferred: flat local variable
local myAddonColor = Color(255, 0, 0)

-- Fast read
local currentColor = myAddonColor
```
Reason: Local variable access is a single register lookup, avoiding table traversals and global environment lookups, making it the fastest for frequent reads.


```lua
local threshold = 100
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- vectors are within the threshold distance
end
```
Reason: Use DistToSqr for squared distance comparison to avoid the costly square root operation.


```lua
for _, ent in ents.Iterator() do
    -- Process each entity
    print(ent:GetClass())
end
```
Reason: Using ents.Iterator() is the wiki-recommended efficient iterator that avoids creating a temporary table of all entities.


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

for _, ent in ipairs(nearbyEnts) do
    -- process entity
end
```
Reason: ents.FindInSphere is a fast built-in spatial query for radius-based entity searches, commonly benchmarked as quicker than FindInPVS for proximity checks.


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local playersInRange = {}

    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            table.insert(playersInRange, ply)
        end
    end

    return playersInRange
end
```

Reason: Iterating over `player.GetAll()` and using `DistToSqr` avoids the overhead of `ents.FindInSphere` scanning all entities, making it faster when many non-player entities exist.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: For loops are optimized in LuaJIT and avoid extra condition checks, making them faster for counting loops.


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

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


```lua
hook.Add("HUDPaint", "DrawHealthOptimized", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end
    local hp = ply:Health()
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, color_white)
    draw.SimpleText("Life: " .. hp, "DermaDefault", 10, 50, color_white)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids three redundant method calls per frame.


```lua
-- Fastest: avoid Color constructor entirely
hook.Add("HUDPaint", "ExamplePaint", function()
    surface.SetDrawColor(255, 255, 255, 255) -- direct RGBA, no allocation
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Calling Color() each frame allocates a new table; passing RGBA directly to surface.SetDrawColor avoids allocation and is faster.


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


```lua
-- Cache LocalPlayer to avoid repeated global lookups
local cachedPlayer = LocalPlayer()

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

-- Example usage
local function UseLocalPlayer()
    if IsValid(cachedPlayer) then
        -- operate on cachedPlayer
    end
end
```
Reason: Caching LocalPlayer in a local variable and updating it once per frame eliminates repeated global table lookups, reducing overhead in frequently called code.


```lua
-- Returns true if ply1 and ply2 are roughly looking at each other.
-- tolerance: 0..1, higher = stricter (1 = perfectly opposite aim vectors)
function ArePlayersLookingAtEachOther(ply1, ply2, tolerance)
    tolerance = tolerance or 0.7 -- default ~45°
    if not IsValid(ply1) or not IsValid(ply2) then return false end

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

    -- Quick reject: aim vectors must point roughly opposite
    if aim1:Dot(aim2) > -tolerance then return false end

    -- Optional positional check: each aims toward the other
    local dir12 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local dir21 = -dir12

    return aim1:Dot(dir12) > tolerance and aim2:Dot(dir21) > tolerance
end
```
Reason: Uses cheap dot‑product checks on aim vectors and optional direction‑to‑target vectors, avoiding expensive math.acos while giving a tunable tolerance for "roughly looking at each other".


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


```lua
Msg("Debug: ", someValue, "\n")
```
Reason: Msg writes directly to the console without the extra function call and newline handling that print does, making it faster in hot paths.


```lua
for i = 1, #tbl do
    local v = tbl[i]
    -- process v
end
```
Reason: Numeric for loop avoids iterator overhead and directly indexes the table, making it the fastest for large sequential arrays.


```lua
-- Fast list pipeline using plain loops and local functions
local function filter(tbl, pred)
    local out, i = {}, 0
    for _, v in ipairs(tbl) do
        if pred(v) then
            i = i + 1
            out[i] = v
        end
    end
    return out
end

local function map(tbl, fn)
    local out = {}
    for i, v in ipairs(tbl) do
        out[i] = fn(v)
    end
    return out
end

-- Example usage: keep even numbers and double them
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 with pre‑allocated tables avoid the overhead of DarkRP's fn combinators (function creation, table copying, and metatable magic), giving lower GC pressure and faster execution for typical filter/map pipelines.


```lua
-- Cache the player list and update only on join/leave
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: Caches player.GetAll() results and refreshes only on PlayerInitialSpawn/PlayerDisconnected, avoiding the O(n) iteration every tick.


```lua
local plyData = {}

local function Set(ply, key, val)
    local idx = ply:EntIndex()
    local t = plyData[idx]
    if not t then
        t = {}
        plyData[idx] = t
    end
    t[key] = val
end

local function Get(ply, key)
    local t = plyData[ply:EntIndex()]
    return t and t[key]
end
```
Reason: Storing per-player data in a global table keyed by EntIndex avoids entity metatable lookups, making reads significantly faster than ply.someField = value.


```lua
local arr = {1,2,3,4,5}
local map = {a=1,b=2,c=3,d=4,e=5}

-- Fast iteration: numeric for loop over sequential array
for i = 1, #arr do
    local v = arr[i]
    -- process v
end

-- Slower iteration: pairs over string-keyed map
for k, v in pairs(map) do
    -- process v
end
```
Reason: Sequential number-indexed arrays allow fast numeric for loops (or ipairs) with O(1) index access, while string-keyed maps require pairs which has higher overhead.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate r,g,b,a numbers avoids Color object creation 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 = {}

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

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

local function GetSteamID(ply)
    return steamIDCache[ply] or ply:SteamID()
end
```
Reason: Caches each player's SteamID on spawn and clears it on disconnect, avoiding repeated calls to the relatively expensive ply:SteamID() method.


```lua
-- Faster string building using a table and table.concat
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece" .. i
end
local bigString = table.concat(pieces)
```
Reason: table.concat builds the final string in one allocation, avoiding the many intermediate strings created by repeated .. concatenation.


```lua
-- Faster rectangle drawing for non-rounded boxes
surface.SetDrawColor(255, 255, 255, 255) -- set color (r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect bypasses the rounded‑box overhead and directly issues a rectangle draw call, making it faster for many non‑rounded rectangles per frame.


```lua
-- Fast single-line text drawing using surface library
local myFont = "DermaDefault"
local text = "Hello, Garry's Mod!"
local x, y = 100, 100

hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont(myFont)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: surface.SetFont + surface.DrawText avoids the extra outline calculations and wrapper overhead of draw.SimpleTextOutlined, making it the fastest per-frame text rendering method.


```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
local t = {1, 2, 3, 4, 5}
-- Clear the table quickly
t = {}
```
Reason: Assigning a new empty table (t = {}) is faster than table.Empty(t) because it avoids iterating over all elements and simply creates a new table, which is cheap in LuaJIT.


```lua
-- Faster membership test using a hash-set (table with keys)
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["cherry"] = true
}

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

-- Example usage
print(hasValue(mySet, "banana"))  -- true
print(hasValue(mySet, "durian"))  -- false
```

Reason: Using a table as a hash-set (keys with true values) gives O(1) average lookup, while table.HasValue scans the list O(n).


```lua
-- Faster: table constructor with known fields
local t1 = { field1 = 1, field2 = 2, field3 = 3 }

-- Slower: create empty table then assign fields
local t2 = {}
t2.field1 = 1
t2.field2 = 2
t2.field3 = 3
```
Reason: Table constructor creates the table and inserts fields in a single operation, avoiding multiple hash lookups and allocations, making it faster for small tables with known fields.


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


```lua
local y = x * x
```
Reason: Multiplication (x * x) is faster than the exponentiation operator (x ^ 2) because ^ invokes a metamethod or C function, while * is a direct VM instruction.


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


```lua
for _, ent in ipairs(ents.GetAll()) do
    if ent:GetClass() == "prop_physics" then
        -- Process entity here
    end
end
```
Reason: `ents.GetAll()` returns an iterable table of all entities, allowing direct iteration without pre-building a separate table.


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


```lua
if IsValid(ent) then
    -- Safe to use
end
```
Reason: Checks if the entity is still valid and active in the game.


```lua
net.Receive("MyAddon.Sync", function(len, msg)
    -- Handle the message here
end)
```
Reason: `net.Receive` is used in Garry's Mod Lua to register a handler for incoming net messages, specifying the message name and a callback function.


```lua
local zeroAngle = Angle(0, 0, 0)
function getZeroAngle()
    zeroAngle.x, zeroAngle.y, zeroAngle.z = 0, 0, 0
    return zeroAngle
end
```
Reason: Reusing a pre-allocated table avoids memory allocation and garbage collection overhead in hot paths.


```lua
local myaddon_color = "red"
local color = myaddon_color
```
Reason: Flat variables avoid table lookups, which are slower than direct memory access for frequent reads.


```lua
ply:GetJob()
```
Reason: `GetJob` is the dedicated DarkRP API for retrieving a player's job name, making it more efficient and reliable than `GetNWString("job")`.


```lua
if vec1:DistanceSquared(vec2) < thresholdSquared then
    -- within threshold
end
```
Reason: Using `DistanceSquared` avoids the computationally expensive square root operation, making the threshold check more efficient.


```lua
local ent = next(entities, nil)
while ent do
    -- Process entity 'ent' here
    ent = next(entities, ent)
end
```
Reason: Using `next(entities, nil)` followed by `next(entities, ent)` iterates through all entities efficiently without loading all into memory, as recommended by Garry's Mod wiki for large entity counts.


```lua
local entities = ents.FindInSphere(player:GetPos(), 100)
```
Reason: `FindInSphere` is a fast built-in spatial query method optimized for checking entities within a spherical radius, making it efficient for proximity checks around a player.


```lua
local players = player.GetAll()
local nearby = {}
for _, ply in ipairs(players) do
    if ply:GetPos():Distance(targetPos) <= radius then
        table.insert(nearby, ply)
    end
end
```
Reason: Directly iterating over players avoids checking all entities, reducing overhead compared to `ents.FindInSphere`.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric for loop in Lua is implemented in C and optimized for range iteration, making it faster than a while loop which requires manual condition checks and variable management.


```lua
hook.Run("MyHook", playerTable)
```
Reason: Reduces function call overhead by batching all players into a single hook invocation instead of per-player calls.


```lua
local health = LocalPlayer():Health()
-- Use 'health' in all three draw calls instead of calling LocalPlayer():Health() each time
```
Reason: Reduces redundant function calls by storing the health value once and reusing it, minimizing overhead in the HUDPaint hook.


```lua
local color = Color(255,255,255)
for i = 1, #entities do
    -- Use 'color' in drawing operations
end
```
Reason: Precomputing the color outside the loop reduces repeated Color function calls, which can improve performance.


```lua
local sin = math.sin
-- Use sin(x) in the loop instead of math.sin(x)
```
Reason: Storing `math.sin` in a local variable reduces global 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 function call overhead by reusing the same instance instead of repeatedly querying it.


```lua
function ArePlayersLookingAtEachOther(a, b)
    local aAim = a:GetAimVector()
    local bAim = b:GetAimVector()
    local aToB = (b:GetPos() - a:GetPos()):GetNormalized()
    local bToA = (a:GetPos() - b:GetPos()):GetNormalized()
    return aAim:Dot(aTo


```lua
ply:SomeHelper()
```
Reason: The colon syntax (ply:SomeHelper()) is the standard method call in Lua, which automatically passes 'ply' as the first argument (self), ensuring correct and efficient execution without additional overhead.


```lua
for i, v in ipairs(array) do
    -- process v
end
```
Reason: ipairs is optimized for sequential integer-keyed tables, avoiding overhead of general key iteration (pairs) or manual index management (numeric for).


```lua
function pipeline(list, filter, map)
    local result = {}
    for _, v in ipairs(list) do
        if filter(v) then
            table.insert(result, map(v))
        end
    end
    return result
end
```
Reason: Combining filter and map into a single loop reduces redundant iterations and function calls compared to separate combinators.


```lua
local cachedPlayers = {}

hook.Add("PlayerJoin", "UpdateCache", function(p) table.insert(cachedPlayers, p) end)
hook.Add("PlayerDisconnect", "UpdateCache", function(p)
    for i, v in ipairs(cachedPlayers) do
        if v == p then table.remove(cachedPlayers, i) break end
    end
end)

-- Use ipairs(cachedPlayers) in your Tick/Think hook instead of player.GetAll()
```

Reason: Caching the player list and updating it only on join/leave events avoids the expensive player.GetAll() call every tick, reducing computational overhead.


```lua
local playerData = {}
function GetPlayerData(ply)
    local uid = ply:UserID()
    playerData[uid] = playerData[uid] or {}
    return playerData[uid]
end
```
Reason: Using a table to cache per-player data reduces repeated access to the ply object's fields, which can be slower due to object lookup overhead. Table lookups are optimized and faster for frequent reads.


```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, avoiding hashing overhead present in string-keyed maps.


```lua
surface.SetDrawColor(255, 0, 0)
```
Reason: Using separate r, g, b values avoids the overhead of creating a Color object, making it faster for performance-critical paths.


```lua
local db = sqlite3.open("playerdata.db")
local stmt = db:prepare("SELECT * FROM players WHERE id = ?")
stmt:execute(123)
local result = stmt:fetch()
db:close()
```
Reason: Local SQLite avoids network latency, making reads/writes faster on a single server.


```lua
local playerSteamIDs = {}
function GetCachedSteamID(ply)
    if not playerSteamIDs[ply] then
        playerSteamIDs[ply] = ply:SteamID()
    end
    return playerSteamIDs[ply]
end
```
Reason: Caching SteamIDs in a table avoids repeated function calls for the same player, reducing overhead in hot paths.


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

Reason: Using `table.concat` after collecting all parts in a table avoids the quadratic time complexity of repeated string concatenation with `..`, which creates new strings each time.


```lua
draw.Rectangle(x, y, w, h)
```
Reason: `draw.Rectangle` avoids the overhead of handling radius calculations present in `draw.RoundedBox`, even with 0 radius.


```lua
surface.DrawText("YourText", x, y, color)
```
Reason: surface.DrawText is optimized for 2D text rendering and typically faster than draw.DrawText for single-line strings due to lower overhead.


```lua
return #myTable
```
Reason: The `#` operator returns the length of a sequence in Lua, which works for sequential array-like tables.


```lua
t = {}
```
Reason: Creating a new table with `t = {}` is O(1) time complexity, while `table.Empty(t)` iterates through all elements (O(n)), making it slower for large tables.


```lua
local set = {}
for _, v in ipairs(list) do set[v] = true end
local exists = set[value] ~= nil
```
Reason: Using a table as a hash set allows O(1) lookups by key, whereas table.HasValue is O(n) for lists.


```lua
local t = {a=1, b=2, c=3}
```
Reason: Initializing the table in the constructor is more efficient as it's a single operation, whereas assigning fields after creation involves multiple assignments.


```lua
function getRandom(t) return t[math.random(1, #t)] end
```
Reason: Directly using math.random to generate an index avoids the overhead of table.Random's function call, making it faster for sequential tables.


```lua
return x * x
```
Reason: Multiplication is faster than function calls like math.pow in tight loops.


```lua
for k, v in pairs(player.GetAll()) do
    -- Process each player 'v' here
end
```
Reason: `pairs(player.GetAll())` iterates over all player objects in the table returned by `player.GetAll()`, which contains all currently connected players.


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


```lua
-- Fast per‑player cache using a weak‑key table and raw access
local playerCache = setmetatable({}, { __mode = "k" }) -- weak keys (player entities)

-- Store a value for a player
local function SetPlayerData(ply, key, value)
    local data = playerCache[ply]
    if not data then
        data = {}
        playerCache[ply] = data
    end
    rawset(data, key, value)          -- raw set avoids metamethod overhead
end

-- Retrieve a value for a player (fast read)
local function GetPlayerData(ply, key)
    local data = playerCache[ply]
    return data and rawget(data, key) -- raw get is a direct table lookup
end

-- Example usage
hook.Add("PlayerInitialSpawn", "InitCache", function(ply)
    SetPlayerData(ply, "score", 0)
end)

hook.Add("SomeEvent", "ReadScore", function(ply)
    local score = GetPlayerData(ply, "score") -- fast read
    -- do something with score
end)
```
Reason: Using a separate weak‑key table with rawget/rawset bypasses the per‑entity field lookup and any metatable overhead, providing much faster frequent reads than ply.someField.


OpenRouter error: openai/gpt-oss-120b:free is temporarily rate-limited upstream. Please retry shortly, or add your own key to accumulate your rate limits: https://openrouter.ai/settings/integrations (code 429)


```lua
-- Faster random element from a sequential (array-like) table
local function fastRandom(tbl)
    local count = #tbl
    if count == 0 then return nil end
    return tbl[math.random(count)]
end

-- Example usage:
local colors = {"red", "green", "blue", "yellow"}
local randomColor = fastRandom(colors)
print(randomColor)
```
Reason: Using `math.random` with the table length avoids the overhead of `table.Random`, which iterates the table; direct indexing is O(1) and thus faster for sequential tables.


OpenRouter error: Internal Server Error (code 500)


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message
    local data = net.ReadTable()
    -- Process data as needed
end)
```
Reason: Registering a net.Receive handler for MyAddon.Sync.


```lua
local len = #myTable
```
Reason: The # operator returns the length of a sequential array-like table in Garry's Mod Lua.


```lua
local ent = FindEntityByClass("prop_physics")
while ent do
    -- Process the entity here
    ent = FindEntityByClass("prop_physics", ent)
end
```
Reason: Uses FindEntityByClass to iterate over all prop_physics entities without prebuilding a table.


OpenRouter free-model daily request cap reached (50 without ≥$10 credits, 1000 with). Wait for UTC day reset or use paid model ids.