```lua
for _, ent in ents.Iterator() do
  if ent:GetClass() == "prop_physics" then
    -- do work on ent
  end
end
```

Reason: `ents.Iterator` walks the entity list one-by-one without materialising a full table, and the class check filters to `prop_physics` inline.


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

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

Reason: Uses hook.Add with the Think hook and the string identifier MyAddon.Think.
```


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then ent:Fire("Use") end
```
Reason: `IsValid` returns false once the entity has been removed, preventing a method call on a stale or NULL reference.


```lua
net.Receive("MyAddon.Sync", function(len)
    -- Example: read a string payload sent by the server
    local payload = net.ReadString()
    print("Received MyAddon.Sync payload:", payload)
    -- Add custom handling logic here
end)
```
Reason: Registers a callback for the `MyAddon.Sync` net message so the client can process data sent from the server.


```lua
local ZERO_ANGLE = Angle(0, 0, 0)
local function GetZeroAngle()
    return ZERO_ANGLE
end

-- or when you need a mutable copy without constructing:
local function CopyZeroAngle()
    return ZERO_ANGLE * 1
end
```
Reason: Caching a single Angle(0,0,0) and returning it (or a cheap copy via `* 1`) avoids repeated userdata allocation that `new Angle()` triggers every call.


```lua
local color = myaddon.config.color  -- read once into local
print(color)
```

Reason: A flat local avoids repeated table lookups (`myaddon.config.color` = two `__index` calls per read), and locals live in registers which Lua's VM accesses faster than hash-table fields.


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

```lua
local jobName = ply:getJobTable().name
-- or
local jobName = ply:getJobTable()["name"]
```

`getJobTable()` is the canonical DarkRP accessor that returns the full job table, whose `.name` field holds the display string. `GetNWString("job")` is fragile: it depends on the server's network-string sync and can return stale or empty results if the NWVar update hasn't arrived yet.

Reason: `getJobTable()` is a direct, synchronous local lookup with no network-variable lag or key-name coupling, making it the idiomatic and reliable way to get a player's job name in DarkRP.


```lua
local distSqr = v1:DistToSqr(v2)
if distSqr < threshold * threshold then
  -- within range
end
```

Reason: `DistToSqr` avoids the `math.sqrt` call inside `Distance`, and comparing squared values against a squared threshold gives the same boolean result with less computation.


```lua
for _, ent in ents.Iterator() do
    -- your logic here
end
```

Reason: `ents.Iterator()` is the wiki-recommended fast Lua-side iterator for `ents.GetAll()` internals — avoids creating a temporary table and GC pressure compared to the alternatives.


```lua
local ents = ents.FindInSphere( ply:GetPos(), 512 )
```

Reason: `ents.FindInSphere` is consistently one of the fastest built-in spatial queries in GMod benchmarks — it uses the engine's spatial partitioning (BVT/broadphase) and avoids the overhead of `FindInPVS` which must resolve PVS visibility per-frame.


```lua
function FindPlayersNear(pos, radius)
    local r2 = radius * radius
    local result = {}
    for _, ply in ipairs(player.GetAll()) do
        local diff = ply:GetPos() - pos
        if diff:LengthSqr() <= r2 then
            result[#result + 1] = ply
        end
    end
    return result
end
```

Reason: `player.GetAll()` iterates a tiny C-managed table (~64-128 max) instead of `ents.FindInSphere` scanning every entity in the PVS, and `LengthSqr()` avoids the sqrt in `Distance`/`DistTo`.


```lua
local i = 0
while i < n do
  i = i + 1
end
```
Reason: The `for` loop (`for i = 1, n do end`) is generally faster because Lua compiles it to dedicated `FORPREP`/`FORLOOP` VM instructions that handle increment and bounds-check in one step, whereas a `while` loop requires separate instructions for comparison, increment, and jump.


```lua
-- FASTER: single hook.Run, all players in one table
-- The hook receives a player list and iterates internally.
-- Only one dispatch + lookup, not N.
hook.Run("NotifyLogic", player.GetAll())

-- SLOWER: N separate hook.Run calls, one per player
-- Each call does its own hook lookup, argument packing, and
-- returns control to this loop N times.
for _, ply in ipairs(player.GetAll()) do
    hook.Run("NotifyLogic", ply)
end
```

Reason: One `hook.Run` call avoids N repeated hook-table lookups, argument marshalling, and Lua call-frame overhead — the single call receives the full player table and the listener iterates it internally.


```lua
hook.Add("HUDPaint", "MyHUD", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText(hp, "DermaLarge", 50, 50, Color(255, 0, 0), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.RoundedBox(4, 50, 80, hp * 2, 20, Color(0, 255, 0))
    draw.SimpleText("HP: " .. hp, "DermaDefault", 50, 110, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```
Reason: Caching `LocalPlayer():Health()` into a local variable avoids two redundant entity method calls, userdata lookups, and C++ engine crossings per frame.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, w, h)
end
```

Reason: Hoisting `Color()` outside the loop avoids a new table allocation (and GC pressure) every frame; `surface.SetDrawColor` also accepts a cached `Color` object directly.


```lua
local sin = math.sin
for i = 1, n do
  -- use sin(x) instead of math.sin(x)
  result[i] = sin(x[i])
end
```
Reason: Local variable lookups bypass the global/table hash-chain traversal that `math.sin` requires on every call.


```lua
-- Cache at file / module scope (runs once per include)
local LocalPlayer = LocalPlayer

-- Then use the cached reference anywhere in the same file
local ply = LocalPlayer()
```

Reason: Assigning the global to a local once per file means Lua resolves a short upvalue instead of a table lookup on the global table every call, which is measurably faster in GLua.


```lua
-- Cheap "are they looking at each other?" check using dot products.
-- Returns true when both players face each other within a tolerance.
-- aimDir must be the unit forward vector from GetAimVector().

local function areMutuallyLooking( ply1, ply2, tolerance )
    tolerance = tolerance or 0.7                       -- cos(≈45°) default
    local v1   = ply1:GetAimVector()
    local v2   = ply2:GetAimVector()
    local d1   = v1:Dot( ( ply2:EyePos() - ply1:EyePos() ):GetNormalized() )   -- ply1 toward ply2
    local d2   = v2:Dot( ( ply1:EyePos() - ply2:EyePos() ):GetNormalized() )   -- ply2 toward ply1
    return d1 >= tolerance and d2 >= tolerance
end
```

Reason: The dot product of a unit direction with a unit-to-target vector equals cos(angle); comparing it directly against a threshold avoids any trig, branch-heavy acos, and intermediate angle storage, making it cache-friendly and ideal for per-tick queries.


```lua
local result = SomeHelper(ply)
```

Reason: A standalone function avoids the overhead of the method-call syntax (`:`) which must resolve the self parameter and index the method on the entity table, and can be inlined or JIT-compiled more aggressively by the LuaJIT engine used by GMod.


```lua
MsgN("DEBUG: ", value)
```

Reason: `print()` builds a Lua table, calls `tostring()` on every argument, and joins them with `table.concat()` before handing the result to `MsgN()` — `MsgN()` is the native C function that does the output directly, skipping all that overhead.


```lua
local t = {...} -- large sequential numeric table
local n = #t
for i = 1, n do
  local v = t[i]
  -- process v
end
```

Reason: Numeric for with `#t` avoids the iterator/lookup overhead that `pairs`/`ipairs` impose on every call, and LuaJIT's trace compiler can JIT-compile it into a tight native loop; `ipairs` adds a metamethod/check per step, `pairs` hashes keys and has undefined order.


```lua
-- DarkRP fn library approach (allocates closures + intermediate tables per call):
local result = fn.Filter(function(ply)
    return ply:Team() == TEAM_CITIZEN
end, player.GetAll())
result = fn.Map(function(ply)
    return ply:Nick()
end, result)

-- Plain Lua pipeline (single pass, zero intermediary allocations):
local out = {}
for _, ply in ipairs(player.GetAll()) do
    if ply:Team() == TEAM_CITIZEN then
        out[#out + 1] = ply:Nick()
    end
end
```

Reason: DarkRP's `fn` combinators create a closure and intermediate table per operation; a single fused loop does the same filter+map with one allocation and no function-call overhead per element.


```lua
local cachedPlayers = {}

hook.Add("PlayerInitialSpawn", "PlayerCache_Refresh", function(ply)
    table.insert(cachedPlayers, ply)
end)

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

hook.Add("Think", "PlayerCache_Think", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- your per-tick logic here
        end
    end
end)
```

Reason: O(n) iteration over a pre-built array avoids the repeated full-table reconstruction and GC pressure that `ipairs(player.GetAll())` imposes every tick.


```lua
-- Entity index storage: Type(ply) lookup → CUserData → direct memory pointer
local meta = FindMetaTable("Entity")
local pmeta = FindMetaTable("Player")
local index = debug.getregistry().Player

-- Preallocate a table indexed by raw entity index (LightUserData key)
local storage = setmetatable({}, { __mode = "k" })

function GetPlayerData(ply)
    local uid = index[ply]
    local t = storage[uid]
    if t then return t end
    t = {}
    storage[uid] = t
    -- Hook cleanup: ply.OnRemove or player_disconnect
    return t
end

-- Usage: GetPlayerData(ply).hp instead of ply.hp
```

Reason: Avoiding `ply.SomeField` skips the `Entity` metatable __index chain and string-key hash lookup entirely; an integer-indexed `LightUserData → table` path resolves in roughly half the time because the Lua VM can use a raw array slot rather than probing the string hash table of the Player userdata.


Answer must contain 0 through 1 candidate loops.

```lua
-- faster: sequential number-indexed array
local items = { "a", "b", "c", "d" }

for i = 1, #items do
  -- use items[i]
end

-- slower: string-keyed map
local map = { a = 1, b = 2, c = 3, d = 4 }

for k, v in pairs(map) do
  -- use v
end
```

Reason: Arrays use the table's contiguous array part with direct index arithmetic, giving O(1) access and CPU-cache-friendly sequential reads; string-keyed maps live in the hash part, requiring a per-entry hash lookup plus string compare on every step, and `pairs()` has higher per-iteration overhead than the `ipairs`/numeric-for path that LuaJIT can trace-optimize into a tight loop.


```lua
surface.SetDrawColor(r, g, b, a)
```

Reason: Passing separate r,g,b,(a) numbers avoids allocating a `Color` userdata per call, skipping GC pressure and constructor overhead in hot draw loops.


Answer must contain 0 through 0 candidate loops.

```lua
local rows = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
if rows then
    for _, row in ipairs(rows) do
        print(row.name, row.score)
    end
end
```

Reason: Local SQLite avoids network round-trips and connection overhead, making reads/writes lower latency than remote MySQL for a single-server setup.


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

function CachedSteamID(ply)
  if not IsValid(ply) then return "" end
  local sid = steamIDCache[ply]
  if sid then return sid end
  sid = ply:SteamID()
  steamIDCache[ply] = sid
  return sid
end
```
Reason: Weak-key table avoids leaks when players disconnect; single table lookup per call beats the C→Lua boundary cost of repeated SteamID() invocations.


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

Reason: `table.concat` builds the final string in one allocation pass, while `..` creates a new temporary string object on every join, costing O(n²) time and memory.


```lua
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` still pushes 6 parameters through Lua→C argument packing and clamps roundness to 0 at runtime; `surface.DrawRect` is a thin direct wrapper that skips the rounding branch entirely, reducing per-call overhead when drawing hundreds of rects per frame.


```lua
-- CACHE outside the draw hook
surface.CreateFont("MyFastFont", {
    font = "Roboto",
    size = 24,
    weight = 500,
})

-- FASTEST: raw surface.* calls — no alignment math, no per-frame font lookup
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("MyFastFont")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText("Hello World")
end)

-- SLOWER: draw.DrawText re-resolves font + alignment every call
-- draw.DrawText("Hello World", "MyFastFont", 100, 100, TEXT_ALIGN_LEFT)

-- SLOWEST: draw.SimpleTextOutlined adds outline passes (4 extra draw calls)
-- draw.SimpleTextOutlined("Hello World", "MyFastFont", 100, 100,
--     TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, Color(0,0,0), Color(255,255,255))
```

Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` skips the per-frame font resolution and alignment arithmetic that `draw.DrawText` performs, and avoids the extra outline draw calls that `SimpleTextOutlined` adds — making the raw `surface.*` triplet the cheapest single-line text draw path.


```lua
local n = #myTable
```

Reason: The `#` operator is the idiomatic and fastest way to get the length of a sequential (integer-keyed, 1-based) table in Lua; `table.getn` was deprecated in Lua 5.1+ and `#table` is the canonical form.


```lua
-- Fastest way to discard a large sequential table:
local t = {}

-- ... fill t with many elements ...

-- Option A: table.Empty(t)   – iterates and nils every key, then you reuse t
-- Option B: t = {}            – a single table swap; the old table becomes garbage

-- The faster approach:
t = {}
```

Reason: `t = {}` is a single pointer reassignment (one allocation, zero iteration), while `table.Empty(t)` must hash-iterate and nil every key then call `rawset`, making it O(n) on the old table plus retaining the same memory footprint until GC collects — for large sequential tables, reassignment is strictly faster and produces less GC pressure when the old table isn't referenced elsewhere.


```lua
local set = {}
for _, v in ipairs(myList) do set[v] = true end

if set[value] then
    -- value exists, O(1) hash lookup
end
```

Reason: Hash-key lookup is O(1) versus table.HasValue's O(n) linear scan with iterator overhead.


Answer must begin its reason with Reason:

```lua
-- Slower: assign fields after construction
local t1 = {}
t1.name = "Alice"
t1.score = 100

-- Faster: use the table constructor
local t2 = {
    name  = "Alice",
    score = 100,
}
```

**Reason:** LuaJIT and PUC Lua both optimise the constructor path — the VM knows at parse time which keys are being set, so it can allocate and populate the hash part in one pass; separate post‑construction assignments trigger additional `SETTABLE`/`SETTABLES` operations and force the VM to re‑hash the table potentially more than once.


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

Reason: `table.Random` iterates the table to count entries and does extra bookkeeping for keyed tables; for a sequential table, indexing `t[math.random(#t)]` is O(1) and avoids that overhead entirely.


```lua
local x2 = x * x
```

Reason: Multiplication is faster than `x^2` (exponentiation) in LuaJIT hot loops, avoiding the `__pow` metamethod fallback and the extra type checks that `math.pow` or `^` may incur.


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

```lua
for _, ply in player.Iterator() do
    -- do something with each player
end
```

Reason: `player.Iterator()` returns a lightweight iterator over all currently connected players without allocating a full table like `player.GetAll()`, making it the preferred modern pattern in Garry's Mod.


```lua
for ent in ents.Iterator("prop_physics") do
  -- process ent
end
```

Reason: `ents.Iterator("prop_physics")` returns a closure-based iterator that yields matching entities one at a time, avoiding the table allocation that `ents.FindByClass` or `ents.GetAll` would incur.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` registers a function to a named hook event; "Think" is the hook event name and "MyAddon.Think" is the unique identifier, allowing the hook to be removed later via `hook.Remove("Think", "MyAddon.Think")`.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid()` checks both that the reference is non-nil and that the entity has not been removed or gone invalid, preventing errors from calling methods on destroyed entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming message
end)
```
Reason: `net.Receive` registers a callback for the named net message; `len` is the message length in bytes and `ply` is the sending player.


```lua
local ZERO_ANGLE = Angle(0, 0, 0)
-- Use ZERO_ANGLE instead of Angle(0,0,0) in hot paths
```

Reason: Constructing `Angle()` in GMod Lua allocates a new userdata object each call, which must be garbage collected later. A cached local reference (`local ZERO_ANGLE = Angle(0,0,0)`) avoids allocation entirely, but you must not mutate it — copy with `ZERO_ANGLE + Angle(0,0,0)` or `Angle(ZERO_ANGLE)` when a writable copy is needed.


```lua
local color = Color(255, 0, 0)
-- read: print(color)
```

Reason: Local variable access requires only a single register load (1 bytecode instruction), while nested table access like `myaddon.config.color` requires multiple hash lookups (3+ table accesses), each O(1) but with significantly higher overhead in the interpreter loop.


```lua
ply:getDarkRPVar("job")
```

Reason: `ply:getDarkRPVar("job")` is the official DarkRP API method that is guaranteed to work across versions, handles nil safely, and won't break if the internal network variable name changes, whereas `ply:GetNWString("job")` directly accesses an undocumented implementation detail.


```lua
if vec1:DistToSqr(vec2) < thresholdSqr then
```
Reason: `DistToSqr` avoids the square root that `Distance` computes internally; comparing squared distance against a pre-squared threshold is mathematically identical and measurably faster, which matters in tight loops like Think hooks or physics callbacks.


```lua
for ent in ents.Iterator() do
    -- process ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator because it avoids allocating a table (unlike `ents.GetAll()`), yields entities one at a time via a closure iterator, and is the preferred pattern when you only need to iterate without storing the entity list.


```lua
local ents = ents.FindInSphere(player:GetPos(), 256)
```

Reason: FindInSphere uses the engine's BSP tree for O(log n) spatial queries and is significantly faster than FindInPVS for small-radius proximity checks, as PVS queries enumerate the entire potentially-visible set regardless of distance.


```lua
local function PlayersInRadius(pos, radius)
    local sq = radius * radius
    local found = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= sq then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: `ents.FindInSphere` queries the engine's spatial partition for ALL entity types (props, NPCs, ragdolls, etc.) and returns hundreds-to-thousands of results that must then be type-filtered; `player.GetAll()` is a cached O(#players) list, and `DistToSqr` avoids the `math.sqrt` call that `Distance` does — minimal work for exactly the subset you need.


```lua
for i = 1, n do end
```
Reason: Lua's numeric `for` is compiled to a single VM instruction (FORPREP/FORLOOP) with the counter kept in a register, whereas `while` generates separate load, compare, add, and jump instructions — more bytecode, more dispatch overhead.


```lua
hook.Run("TickNotify", player.GetAll())
```

Reason: `hook.Run` pays the cost of hook-table lookup and iteration once; calling it per-player multiplies that overhead by player count.


```lua
local hp = LocalPlayer():Health()
draw.SimpleText(hp, "DermaDefault", 10, 10)
draw.SimpleText(hp, "DermaDefault", 10, 30)
draw.SimpleText(hp, "DermaDefault", 10, 50)
```

Reason: Cache `LocalPlayer():Health()` in a local variable to avoid three redundant method calls per frame, as each call crosses the Lua-C boundary and allocates a new number object.


```lua
local WHITE = Color(255,255,255)
-- inside paint loop: use WHITE instead of Color(255,255,255)
```

Reason: Calling `Color()` allocates a new table and 4 userdata objects per call. Hoisting it to a local outside the loop eliminates per-frame GC pressure and allocation overhead.


```lua
local sin = math.sin
for i = 1, 1e6 do
    local x = sin(i)
end
```

Reason: Lua table lookups (`math.sin`) are slower than local variable access; caching the function in a local eliminates the hash lookup on every iteration.


```lua
local lp = LocalPlayer()
-- use lp instead of LocalPlayer() throughout
```

Reason: `LocalPlayer()` is a C-side global lookup that walks the entity list each call; caching it in a local variable eliminates that overhead and turns every subsequent reference into a single upvalue access.


```lua
function LookingAtEachOther(a, b, t)
    t = t or 0.5
    local av = a:GetPos() + a:GetViewOffset()
    local bv = b:GetPos() + b:GetViewOffset()
    local d = (bv - av):GetNormalized()
    local e = (av - bv):GetNormalized()
    return a:GetAimVector():Dot(d) > t and b:GetAimVector():Dot(e) > t
end
```

Reason: Dot product comparison avoids math.acos and its NaN edge case when rounding errors push the quotient past ±1, while being branchless and trivially inlinable.


```lua
SomeHelper(ply)
```
Reason: `ply:SomeHelper()` requires a metatable method lookup on `ply` each call, while `SomeHelper(ply)` is a direct function call (especially fast if the function is a local) with zero table lookups.


```lua
MsgN("debug line")
```

Reason: `MsgN` bypasses `print`'s formatting overhead (tostring calls on each arg, tab joining, implicit newline handling) and writes directly to the console via a lower-level C binding.


```lua
for i = 1, #t do
    local v = t[i]
end
```
Reason: Numeric `for` avoids iterator function calls (`pairs` calls `next` each iteration, `ipairs` calls its stateful iterator) and directly indexes the array, which is the fastest in Lua's VM.


```lua
-- Slow: fn combinator style (multiple intermediate tables + closure overhead)
local result = fn.Compose(
  fn.Map(fn.Curry(ply.GetCount, "pistol")),
  fn.Filter(fn.Curry(operator.gt, 3))
)(players)

-- Fast: single pass with result accumulation
local result = {}
for i = 1, #players do
  local count = players[i]:GetCount("pistol")
  if count > 3 then result[#result + 1] = count end
end
```
Reason: fn creates one intermediate table and closure per transform step, plus variable-arity overhead from LuaJIT's trace compiler giving up on `select`/`unpack` hotpaths; a single `for i = 1, #t do` loop with inline branching stays within LuaJIT's trace budget (one trace, no side exits for closure calls) and avoids all intermediate allocations.


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

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

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

-- In your Think/Tick hook:
hook.Add("Think", "MyThink", function()
    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        -- operate on ply
    end
end)
```

Reason: `player.GetAll()` allocates a new table every call; caching it and invalidating only on join/leave avoids per-tick table allocation for O(1) amortized cost instead of O(n) allocs per tick.


```lua
-- Fast: plain local table, ply as key, no metatable overhead
local data = {}
data[ply] = value  -- write
local x = data[ply] -- read
```

Reason: The ply metatable has __index/__newindex handlers; `ply.field` traverses those on every access. A plain local table with the ply object as key is a direct hash lookup in a table with no metatable at all, avoiding any dispatch overhead for both reads and writes.


```lua
-- Fast: sequential number-indexed array (array part, O(n) contiguous iteration)
for i = 1, #arr do end
-- or
for _, v in ipairs(arr) do end

-- Slow: string-keyed map (hash part, per-element hashing + indirection)
for k, v in pairs(map) do end
```

Reason: Lua tables store sequential integer keys from 1 in a contiguous array part accessible via direct indexing, while string-keyed entries live in a hash table requiring hash computation, collision resolution, and pointer chasing on every access — the array path is branch-predictor friendly and cache-local.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing raw number arguments avoids Color object allocation and table construction overhead, reducing GC pressure in a hot draw path.


```lua
local result = sql.Query("SELECT * FROM players WHERE steamid = " .. SQLStr(plySteamID64))
```
Reason: Local SQLite avoids network round-trip latency entirely — every MySQL query adds at least one TCP send/recv to a remote process, while SQLite reads/writes directly to a local file with zero network overhead.


```lua
do
  local mt = findmeta("Player")
  local old = mt.__index
  mt.__index = function(self, k)
    if k ~= "_CachedSteamID" then return old(self, k) end
    local sid = self:SteamID()
    rawset(self, "_CachedSteamID", sid)
    self._CachedSteamID = sid
    return sid
  end
end

-- Use ply._CachedSteamID everywhere on the hot path.
-- Populated on first access, never calls SteamID() again.
hook.Add("PlayerDisconnected", "CleanSteamIDCache", function(ply)
  ply._CachedSteamID = nil
end)
```
Reason: `SteamID()` allocates and formats a string on every call; caching it as a raw field on the player metatable via `__index` avoids the call after first access, with zero changes to existing call sites and automatic cleanup on disconnect.


```lua
-- Slow: repeated .. concatenation
local s = ""
for i = 1, 10000 do
    s = s .. "piece" .. i
end

-- Fast: table.concat
local parts = {}
for i = 1, 10000 do
    parts[i] = "piece" .. i
end
local s = table.concat(parts)
```

Reason: Repeated `..` creates a new string for each operation (O(n²) copying), while `table.concat` allocates once after computing the final length (O(n)).


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` internally still computes rounded-corner geometry before falling through to a rect; `surface.DrawRect` skips that overhead and goes straight to the GPU with one draw call.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 10)
surface.DrawText("Hello, world!")
```
Reason: surface.* functions call the engine's text rasterizer with zero wrapper overhead, while draw.DrawText and SimpleTextOutlined add Lua function call indirection / alignment parsing / outline passes.


CLI exited without a valid strict response.


```lua
t = {}
```
Reason: `t = {}` is O(1) — it creates a new empty table and lets the old one be garbage collected — while `table.Empty(t)` is O(n) because it iterates and removes every element.


```lua
-- Fast: O(1) lookup using a set (dictionary)
local set = { apple = true, banana = true, cherry = true }
if set[value] then
    -- value exists
end

-- Slow: O(n) iteration using table.HasValue
local list = { "apple", "banana", "cherry" }
if table.HasValue(list, value) then
    -- value exists
end
```

Reason: A lookup table (dictionary) uses hash-based O(1) key access, while `table.HasValue` performs a linear O(n) scan through the entire list, making the set approach drastically faster for large collections.


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

Reason: Table constructor emits a single `NEWTABLE` + `SETLIST` bytecode sequence, whereas field assignments after `{}` generate one `SETTABLE` instruction per field, each requiring a full hash lookup and method call overhead.


```lua
local t = {"a", "b", "c", "d", "e"}
local rand = t[math.random(#t)]
```

Reason: `table.Random` calls `table.GetKeys` internally to handle non-sequential tables, which allocates and populates a new array of all keys — an O(n) memory and time cost you pay even for sequential tables. `math.random(#t)` directly indexes the array in O(1) with zero allocation.


```lua
local s = x * x
```
Reason: `x * x` avoids function call overhead (`math.pow`) and LuaJIT's expensive exponentiation opcode (`^`), compiling to a single VM instruction that the JIT can inline and strength-reduce.


```lua
for ply in player.Iterator() do
    -- ply is a Player object
end
```

Reason: `player.Iterator()` is the modern GMod idiom — it avoids allocating the intermediate table that `player.GetAll()` creates, uses a stateless iterator instead of `pairs`, and is the canonical way to iterate players in current Garry's Mod Lua.


```lua
for ent in ents.Iterator("prop_physics") do
	-- ent is each prop_physics entity
end
```

Reason: `ents.Iterator` creates a cursor-based iterator that yields matching entities one at a time from the internal entity list, never allocating a table of all entities.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: hook.Add registers a function to be called on the specified event, where the identifier allows the hook to be uniquely removed or overridden later.


```lua
if IsValid(ent) then
```

Reason: In Garry's Mod, `IsValid` checks both that the reference is not nil and that the entity has not been removed or is in a valid state, preventing errors from calling methods on invalid entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadTable()
    -- process the received data
end)
```
Reason: `net.Receive` registers a callback for the named net message on both client and server; `len` holds the message length and `ply` is the sender (server-side) or nil (client-side).


```lua
-- Cache: allocate once outside the hot path
local zero_angle = Angle()

-- Hot path: reuse instead of allocating a new Angle() each time
zero_angle:Set(0, 0, 0)
-- ... use zero_angle ...
```
Reason: `Angle()` allocates a new userdata and triggers GC pressure each call; `:Set(0,0,0)` writes three floats into an existing allocation — zero heap churn, zero GC, and the same result.


```lua
-- Declaration
local color = Color(255, 0, 0)

-- Read
draw.SetDrawColor(color)
```

Reason: A local variable is a register read (single VM instruction), while `myaddon.config.color` chains three hash-table lookups (each requiring key hashing, bucket probing, and type checks), making locals 5–20× faster in LuaJIT.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP's own `getDarkRPVar` method is the official API that abstracts the internal netvar implementation — `ply:GetNWString("job")` ties your code to a private implementation detail that could change between DarkRP versions.


```lua
local thresholdSqr = threshold * threshold
if vec1:DistToSqr(vec2) < thresholdSqr then
    -- within range
end
```
Reason: `DistToSqr` avoids the expensive `sqrt()` call since comparing squared distances is equivalent for threshold checks and is significantly faster.


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator that avoids allocating the full entity table via `ents.GetAll()`, using a C-side iterator instead.


```lua
local ents = ents.FindInSphere(vPlayer:GetPos(), 512)
```
Reason: `FindInSphere` is the fastest general-purpose spatial query — it performs a simple radius check against the engine's spatial partition tree, avoiding the cost of PVS bit-vector construction and visibility traversal inherent to `FindInPVS`, making it consistently faster for arbitrary point-based entity lookups in benchmarks.


```lua
local function GetPlayersInRadius(pos, radius)
    local rsq = radius * radius
    local out = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:IsValid() and ply:GetPos():DistToSqr(pos) <= rsq then
            table.insert(out, ply)
        end
    end
    return out
end
```
Reason: `ents.FindInSphere` must traverse the full entity spatial hash and scan every entity type (props, ragdolls, NPCs, vehicles) inside the sphere before filtering to players, while `player.GetAll()` iterates only the player list directly and uses squared-distance comparison to skip the sqrt, making it O(n_players) with zero dead work regardless of total entity count.


Answer must contain 1 through 1 candidate loops.

```lua
-- faster: numeric for loop
for i = 1, n do end

-- slower: while loop with manual counter
local i = 1
while i <= n do
  i = i + 1
end
```
Reason: LuaJIT compiles the numeric `for` loop to a single opcode with internal counter storage, avoiding the extra bounds check, increment, and local-variable overhead that the `while` loop requires each iteration.


```lua
hook.Run("TickCustomLogic", player.GetAll())
```

Reason: Calling hook.Run once avoids paying the hook dispatch overhead (function lookup, call loop setup, return-value handling) N times per tick; the single call lets the hook receiver iterate the list itself, which is strictly cheaper than repeating the dispatch machinery per player.


```lua
local ply = LocalPlayer()
local health = ply:Health()
draw.DrawText("HP: " .. health, "DermaLarge", 10, 10, Color(255, 255, 255))
draw.DrawText("Health: " .. health, "DermaDefault", 10, 50, Color(255, 255, 255))
draw.SimpleText(health, "DermaDefault", 10, 100, Color(255, 0, 0))
```

Reason: `LocalPlayer():Health()` involves crossing the Lua/C boundary and potentially reading from shared memory each call. Caching the value in a local variable eliminates two redundant `NetworkedVar` lookups, which is the single biggest perf win for per-frame code in GMod.


```lua
local col = Color(255, 255, 255)
-- inside paint loop: surface.SetDrawColor(col)
```
Reason: `Color(...)` allocates a new table every call; hoisting it outside the loop eliminates per-frame allocation and GC pressure.


```lua
local sin = math.sin
```
Reason: Localizing avoids global table lookup for `math` and member lookup for `sin` each iteration, reducing it to a single upvalue access.


```lua
local ply = LocalPlayer()
```

Reason: LocalPlayer() is a C call that traverses the entity lookup table; caching it in a local variable replaces that O(n) table walk with an O(1) register lookup on every subsequent use.


```lua
local function LookingAtEachOther(plyA, plyB, cosAngle)
    cosAngle = cosAngle or 0.5
    local dir = (plyB:GetPos() - plyA:GetPos()):GetNormalized()
    local aimA = plyA:GetAimVector()
    local aimB = plyB:GetAimVector()
    return aimA:Dot(dir) >= cosAngle and aimB:Dot(-dir) >= cosAngle
end
```

Reason: Replaces two math.acos calls (angle-between) with two dot-product comparisons against a precomputed cosine threshold — dot product is a single multiply-add per axis, avoiding acos entirely by checking cos-angle directly.


```lua
SomeHelper(ply)
```
Reason: Standalone function calls avoid the metatable method lookup overhead (FindMetaTable + function index) incurred by colon-style method calls on player objects.


```lua
local Msg = Msg
```
Reason: `print()` concatenates all arguments with tabs and appends a newline via string formatting before calling the internal C output function, then resolves the global `print` symbol on every call; a locally cached `Msg` writes raw strings directly without formatting, avoiding both the string overhead and the global table lookup.


```lua
for i = 1, #t do
  local v = t[i]
end
```
Reason: Numeric for avoids iterator function call overhead entirely (no closure per loop, no `next()` or C iterator dispatch) and directly indexes the array — `pairs()` uses generic `next()` with hash lookup on every key, while `ipairs()` still pays the per-iteration C-call overhead of its iterator.


```lua
-- Slow: fn approach
-- local result = fn.Map(fn.Filter(players, fn.Curry(isNear, 100)), fn.Compose(fn.GetName, fn.Curry(format, "VIP: %s")))

-- Fast: single loop
local result = {}
for i = 1, #players do
  local p = players[i]
  if isNear(p, 100) then
    result[#result + 1] = "VIP: " .. p:Name()
  end
end
```

Reason: `fn` creates a new closure per combinator per call, thrashing the Lua allocator and GC; a single `for` loop with inline conditions and concatenation avoids all closure/allocation overhead and is 3-10x faster in GLua's JIT-averse environment.


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

local function refresh()
    ply_cache = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "PlyCache", refresh)
hook.Add("PlayerDisconnected", "PlyCache", refresh)

hook.Add("Think", "MyThink", function()
    for i = 1, #ply_cache do
        local ply = ply_cache[i]
    end
end)
```

Reason: Avoids allocating a new table (player.GetAll()) and iterator object (ipairs) every tick — ~60–66× fewer allocations per second. The hooks refresh the cache only when the player list actually changes, so the hot path is a single length read and a raw integer loop over a Lua array with no GC pressure.


```lua
local playerData = {}
-- Write:
playerData[ply:EntIndex()] = value
-- Read:
local val = playerData[ply:EntIndex()]
```
Reason: `ply.SomeField` triggers C-side metatable dispatch on every read; storing in a Lua table with `ply:EntIndex()` (a small integer) uses the array part of the table, avoiding string-key hashing and the Player metatable overhead entirely.


```lua
-- string-keyed map
for k, v in pairs(map) do end

-- sequential number-indexed array
for i, v in ipairs(arr) do end
```

Reason: Sequential numeric arrays use Lua's internal array part and are iterated with `ipairs`, which is a direct memory walk; string-keyed maps live in the hash part and require `pairs`, which hashes each key and traverses collided buckets, making arrays roughly 2–5× faster depending on table size.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing raw numbers avoids creating a Color table object, eliminating per-call heap allocation and GC pressure in hot draw paths.


```lua
sql.Query("SELECT steamid, kills, deaths FROM gmod_players WHERE steamid = 'STEAM_0:1:12345'")
```

Reason: SQLite runs in-process with zero network overhead, while remote MySQL requires a TCP round-trip to a separate host, which adds 0.5-50ms of network latency per query depending on distance and connection quality.


```lua
local steam_cache = setmetatable({}, { __mode = "k" })
local function SteamID(ply)
    local id = steam_cache[ply]
    if id then return id end
    id = ply:SteamID()
    steam_cache[ply] = id
    return id
end
hook.Add("PlayerDisconnected", "SteamIDCacheCleanup", function(ply) steam_cache[ply] = nil end)
```
Reason: `ply:SteamID()` involves a C-side string format call on every invocation; caching by weak-key table avoids repeated work, and `PlayerDisconnected` cleanup prevents stale references without leaking.


```lua
-- Slow: repeated .. concatenation creates many intermediate strings
local s = ""
for i = 1, 10000 do
    s = s .. "piece"
end

-- Fast: table.insert pieces then table.concat once
local t = {}
for i = 1, 10000 do
    t[#t + 1] = "piece"
end
local s = table.concat(t)
```

Reason: `table.concat` allocates the final string once by computing the total length upfront, avoiding O(n²) memory churn from repeated `..` which creates a new intermediate string on every iteration.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox` always computes rounded corner geometry even at radius 0; `surface.DrawRect` goes straight to the GPU with no branching or vertex math.


```lua
surface.CreateFont("OptFont", {font = "Arial", size = 20})
surface.SetFont("OptFont")
surface.SetTextColor(255, 255, 255)
hook.Add("HUDPaint", "FastText", function()
    surface.SetTextPos(10, 10)
    surface.DrawText("single line")
end)
```

Reason: `surface.DrawText` is the rawest render call with no wrapper overhead; `draw.DrawText` calls `surface.SetFont` and `surface.SetTextColor` internally every frame, and `SimpleTextOutlined` adds outline geometry on top, making it the slowest.


```lua
#t
```

Reason: The `#` operator (length operator) is O(log n) and the idiomatic choice for sequential arrays in Lua/GMod, while `table.Count()` is O(n) and intended for key-value tables.


```lua
t = {}
```
Reason: `t = {}` is O(1) — it simply creates a new empty reference and leaves the old table to the GC — while `table.Empty(t)` is O(n) because it iterates every key to remove it in-place.


```lua
-- Slow: O(n) linear scan
local slow = table.HasValue(list, value)

-- Fast: O(1) hash lookup
local fast = set[value] ~= nil
```

Reason: `table.HasValue` scans the entire list linearly (O(n)), while a lookup table built with `local set = {}; for _, v in ipairs(list) do set[v] = true end` lets you check existence via a single hash lookup (O(1)), which is dramatically faster for repeated membership tests.


```lua
-- Faster: fields in constructor
local t = {a = 1, b = 2}

-- Slower: assign after {}
local t = {}
t.a = 1
t.b = 2
```

Reason: The table constructor compiles to a single `NEWTABLE` with a hinted size followed by direct array/hash slot fills, avoiding the per-assignment hash lookup and table reallocation that individual assignments incur.


```lua
t[math.random(#t)]
```
Reason: `table.Random` handles both sequential and key-value tables with extra type checks and fallback logic; for a known sequential table, direct `math.random(#t)` + indexing skips all that overhead.


```lua
local result = x * x
```
Reason: Direct multiplication compiles to a single machine instruction in LuaJIT, avoiding the function call and exponentiation-table lookup of `x ^ 2` or `math.pow(x, 2)`.


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

```lua
for _, v in ipairs(player.GetAll()) do
    -- v is each player
end
```
Reason: `player.GetAll()` returns a sequential array table, so `ipairs` is more correct and performant than `pairs`, which wastes work on the hash-key iteration path.


```lua
for ent in ents.Iterator("prop_physics") do
    -- process ent
end
```
Reason: `ents.Iterator` returns a direct iterator over matching entities without allocating a table, unlike `ents.FindByClass` which builds one.


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

Reason: `hook.Add` registers a named callback on the Think hook; the second argument is the unique identifier, matching the requested `MyAddon.Think`.


```lua
if IsValid(ent) then
```

Reason: `IsValid()` checks that the entity is not nil, is of an entity type, and has not been removed or marked for removal, preventing errors like "Tried to use an entity that was not valid" when calling methods on a nil or removed entity.


```lua
net.Receive("MyAddon.Sync", function(len, ply) end)
```
Reason: `net.Receive` is the standard GMod function to register a callback when a net message of a given name arrives from a client (`ply` is the sender, `len` is the message length).


```lua
local ZERO_ANGLE = Angle()

-- Hot path: reuse the cached zero angle instead of Angle(0, 0, 0)
local ang = ZERO_ANGLE
```
Reason: `Angle()` allocates a new table with three writes plus GC pressure; a cached local avoids all allocation and is a single reference copy.


```lua
local color = MyAddonConfigColor -- declare once at top of file
local current = color -- read
```

Reason: A local variable is a single SLOAD op in LuaJIT (register slot, no hash lookup), while nested tables require chained HLOAD ops — one hash probe per dot — making locals ~3-10x faster on hot read paths.


```lua
ply:getDarkRPVar("job")
```
Reason: `ply:GetNWString("job")` reads the network string directly, which bypasses DarkRP's caching and compatibility layer and will not work if the network variable name ever changes; `ply:getDarkRPVar("job")` is the official DarkRP API that returns the cached job name string and is guaranteed to remain stable across DarkRP versions.


```lua
if a:DistToSqr(b) < thresholdSqr then
    -- within threshold
end
```

Reason: `DistToSqr` avoids the expensive `sqrt` call that `Distance` performs; squaring the threshold once and comparing squared distances is strictly cheaper when only a comparison is needed.


```lua
for ent in ents.Iterator() do
    -- process ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator because it runs a C-side iterator over the internal entity array without allocating a table, unlike `ents.GetAll()` which creates a new table on every call.


```lua
local ents = ents.FindInSphere(ply:GetPos(), 256)
```

Reason: `FindInSphere` with a small radius (≤512) avoids the expensive world visibility scan of `FindInPVS` and uses a simple spatial lookup that is typically 2-4x faster for nearby queries in benchmarks.


```lua
local function PlayersInRadius(pos, radius)
    local radiusSq = radius * radius
    local near = {}
    local plypos = Vector(0, 0, 0)
    for _, ply in ipairs(player.GetAll()) do
        plypos = ply:GetPos()
        if plypos:DistToSqr(pos) <= radiusSq then
            near[#near + 1] = ply
        end
    end
    return near
end
```
Reason: `ents.FindInSphere` iterates over *all* entities on the server (props, ragdolls, npcs, etc.), which is O(all ents). Iterating only `player.GetAll()` limits the loop to O(players) — a vastly smaller set when many non-player entities exist — and avoids intermediate table allocation from the ents filter. Using `DistToSqr` removes a `sqrt` per check.


```lua
for i = 1, n do end
```

Reason: In LuaJIT (which GMod uses), the numeric `for` loop compiles to specialized bytecode (`FORPREP`/`FORLOOP`) that the JIT compiler recognizes as a tight counting loop, enabling optimizations like loop unrolling and eliminating the separate counter increment and condition check that `while` requires.


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

-- Slow: looping and calling hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("PlayerTickPerPlayer", ply)
end
```
Reason: `hook.Run` incurs internal dispatch overhead (hook table lookup, function call validation, and argument marshaling) per invocation; batching all players into one call avoids that overhead for every player beyond the first, which matters at 66+ ticks/second with 32–128 players.


```lua
local ply = LocalPlayer()
local health = ply:Health()
-- draw call 1 using health
-- draw call 2 using health
-- draw call 3 using health
```
Reason: Caches `LocalPlayer()` and `Health()` in locals, avoiding three redundant method lookups and C function calls across the frame.


```lua
local WHITE = Color(255,255,255)
hook.Add("PostDrawOpaqueRenderables", "Example", function()
    -- use WHITE instead of Color(255,255,255)
end)
```

Reason: `Color()` allocates a new table each call; caching it once in a local avoids per-frame GC pressure and table allocation.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```
Reason: Caching `math.sin` in a local variable avoids the global/table hash lookup on every iteration, since local variable access from the register array is significantly faster than table indexing.


```lua
local LocalPlayer = LocalPlayer
local ply = LocalPlayer()
-- then use ply instead of calling LocalPlayer() repeatedly
```
Reason: `LocalPlayer()` performs a C-side lookup through the entity system each call; caching it to a local variable avoids that overhead and also benefits from Lua's local variable access being faster than global table lookup. Call `LocalPlayer()` again only when the player instance could change (e.g., map change, respawn).


```lua
local function LookingAtEachOther(a, b, threshold)
  threshold = threshold or 0.95
  local dir = (b:GetPos() - a:GetPos()):GetNormalized()
  return a:GetAimVector():Dot(dir) > threshold and b:GetAimVector():Dot(-dir) > threshold
end
```
Reason: A dot product directly gives the cosine of the angle between two unit vectors, so comparing it to a threshold (e.g. 0.95 ≈ 18°) avoids the expensive `math.acos` call while being a monotonic equivalent check.


```lua
SomeHelper(ply)
```
Reason: Method call syntax `ply:SomeHelper()` desugars to `ply.SomeHelper(ply)`, requiring a metatable hash lookup every call, while a plain function call `SomeHelper(ply)` is a direct closure reference with zero indirection.


```lua
MsgN("debug: ", someVar)
```
Reason: `print()` in GMod internally calls `tostring` on every argument and adds a newline via `MsgN`, so calling `MsgN` directly skips that wrapper overhead. For a hot path, hoist the call behind a `Dev(1)` or `CVAR` guard to avoid the string formatting entirely when debug is off.


```lua
for i = 1, #t do local v = t[i] end
```
Reason: Numeric `for` avoids the per-iteration function call overhead of `pairs`/`ipairs` iterators and the closure allocation, compiles to a single native loop instruction in Lua's VM, and is the only option with O(1) overhead per element.


```lua
-- Instead of: fn.Filter(fn.Compose({fn.Curry(fn.Not, fn.Curry(fn.Eq, ""))(fn.Prop("name"))), fn.Map(fn.Prop("license"))))(players)
local result, ent = {}
for i = 1, #players do
  ent = players[i]
  if ent and ent:IsValid() and ent.name and ent.name ~= "" then
    result[#result + 1] = ent.license
  end
end
```

Reason: `fn` composes anonymous closures per element, thrashing the LuaJIT compiler's trace budget and preventing JIT compilation; a single plain loop stays within a single trace, avoids per-element closure allocation, and runs 3–10× faster across realistic list sizes.


```lua
local cached_players = {}

local function refresh_player_cache()
  cached_players = player.GetAll()
end

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

hook.Add("Think", "MyThink", function()
  for i = 1, #cached_players do
    local ply = cached_players[i]
    -- use ply directly, no ipairs overhead
  end
end)
```

Reason: `ipairs(player.GetAll())` allocates a new iterator closure and table lookup every tick; caching the table and refreshing on join/leave events (PlayerInitialSpawn/PlayerDisconnected) eliminates the per-tick allocation and lookup, and using a numeric `for` loop avoids ipairs's iterator overhead entirely.


```lua
local pdata = {}; local idx = ply:EntIndex()
pdata[idx] = value          -- write
local val = pdata[idx]      -- read
```
Reason: `ply.x` traverses GMod's entity metatable on every read; a local table keyed by `EntIndex()` resolves in one raw hash lookup with zero metatable overhead.


```lua
-- Fastest: sequential number-indexed array with numeric for loop
local t = {"a", "b", "c"}
for i = 1, #t do
  local v = t[i]
end
```
Reason: Lua stores the array part of a table in a contiguous C array accessed by index directly, while string-keyed maps require computing a hash for every key lookup during iteration, making sequential numeric arrays ~2-3x faster for iteration in LuaJIT (which Garry's Mod uses).


```lua
surface.SetDrawColor(r, g, b)
```
Reason: Passing raw numbers avoids allocating a Color table and its metatable setup, which is measurable in a hot loop.


```lua
local result = sql.Query("SELECT data FROM player_data WHERE steamid = '" .. SQLStr(ply:SteamID()) .. "'")
```

Reason: SQLite runs in-process with no network round-trip, avoiding TCP connection overhead, authentication handshake, and inter-process communication that MySQL requires even on loopback.


```lua
-- Cache SteamID on the player object (PMeta)
-- Call once per player spawn / first access
function GM:PlayerInitialSpawn(ply)
    ply._SteamID = ply:SteamID()
end

-- Hot-path replacement
local function GetCachedSteamID(ply)
    return ply._SteamID
end
```
Reason: `ply:SteamID()` calls into engine C-side which does a hash-table lookup and string allocation each time. Caching as a table-keyed string on the Player metatable (`ply._SteamID`) reduces the hot path to a single table read—no C call, no allocation, no GC pressure.


```lua
-- Slow: repeated .. concatenation
local s = ""
for i = 1, 10000 do
    s = s .. "piece" .. i
end

-- Fast: table.concat (avoids O(n²) reallocations)
local t = {}
for i = 1, 10000 do
    t[#t + 1] = "piece"
    t[#t + 1] = i
end
local s = table.concat(t)
```
Reason: Lua strings are immutable; `..` creates a new string each time, yielding O(n²) time and allocation. `table.concat` precomputes the total length, allocates once, and fills the buffer in O(n).


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` still enters the rounded-box shader path with vertex calculations for bezier corner segments, whereas `surface.DrawRect` calls the native rectangle rasterizer directly, skipping the branching and math that a general-purpose rounded-box function pays for even at radius 0.


```lua
surface.SetFont("DermaLarge")
surface.SetTextColor(color_white)
surface.SetText(pos)
surface.DrawText(x, y)
```
Reason: Direct `surface.*` calls skip `draw.DrawText`'s internal table unpacking, color copy, and argument validation, and avoid `SimpleTextOutlined`'s multi-pass outline rendering — each wasted op per frame compounds into measurable stutter in a hot draw loop.


```lua
#tbl
```
Reason: The `#` operator is the idiomatic, O(1) built-in for sequential tables; `table.Count` is O(n) and intended for associative tables.


```lua
t = {}
```
Reason: `t = {}` is O(1) — it assigns a new empty table without iterating, whereas `table.Empty(t)` is O(n) because it must walk and clear every element in-place. The allocation and GC cost of the discarded table is negligible for large tables and amortizes across frames.


```lua
local set = { ["someKey"] = true, ["anotherKey"] = true }
if set["someKey"] then end -- O(1) lookup
```

Reason: `table.HasValue` iterates the entire list linearly (O(n)), while a lookup table uses Lua's hash-based table access (O(1)), avoiding any loop.


```lua
-- Faster: put fields in the constructor
local t = {a = 1, b = 2, c = 3}

-- Slower: assign after {}
local t = {}
t.a = 1
t.b = 2
t.c = 3
```
Reason: The table constructor avoids multiple hash-lookup assignments and is optimized in the Lua VM to set fields during table creation, reducing overhead from repeated metatable checks and memory barrier calls.


```lua
tbl[math.random(#tbl)]
```
Reason: `table.Random` extracts all keys into an array (O(n) overhead and allocation), then picks one; for a sequential table, a direct indexed access with `math.random(#tbl)` is O(1) with zero allocation.


```lua
local s = x * x
```

Reason: `x * x` avoids the `x ^ 2` metamethod overhead and `math.pow` function call — LuaJIT compiles multiplication to a single `vmulsd` instruction, while exponentiation goes through a C call or generic arithmetic fallback.


```lua
for _, ply in ipairs(player.GetAll()) do
  -- use ply
end
```
Reason: `ipairs` is the correct iterator for `player.GetAll()` because it returns a numerically-indexed array, and `pairs` on an array incurs unnecessary hash lookup overhead.


```lua
for ent in ents.Iterator("prop_physics") do
end
```
Reason: `ents.Iterator` yields entities via an internal cursor without allocating a table, unlike `ents.FindByClass` which builds a table of every match (and indirectly all entities).


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add("Think", "MyAddon.Think", fn)` registers `fn` to execute every tick during the "Think" hook, uniquely identified by "MyAddon.Think".


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: `IsValid` checks that the entity exists, is not being removed, and is not a NULL entity, preventing errors from calling methods on invalid references.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: net.Receive is the standard GMod function to register a handler for incoming net messages, where the first argument is the message name string and the second is a callback receiving the message length and the sending player.


```lua
local angle_new = Angle
-- Then in hot path: local a = angle_new(0, 0, 0)
```

Reason: Caching the `Angle` global as a local variable avoids a global table lookup and metamethod dispatch on every call in a hot path.


```lua
local color = Color(255, 0, 0)
print(color)
```

Reason: Local variable access is a single LOAD instruction in Lua VM, while nested table lookups require a hash lookup per level (myaddon → config → color), making locals an order of magnitude faster for hot reads.


```lua
ply:getDarkRPVar("job")
```
Reason: `getDarkRPVar` is DarkRP's own API for accessing job data and is guaranteed to work across versions, while `ply:GetNWString("job")` relies on an internal network string name that is not part of DarkRP's public API and may break on update or not reflect the true job if the internal variable name changes.


```lua
if pos:DistToSqr(target) < threshold ^ 2 then
```
Reason: `DistToSqr` avoids the expensive `math.sqrt` call since comparing squared distances against a squared threshold is mathematically equivalent and significantly faster.


```lua
for ent in ents.Iterator() do
end
```
Reason: `ents.Iterator()` avoids allocating the full entity table that `ents.GetAll()` creates, so it is the wiki-recommended efficient iterator for visiting every entity, with the only downside being you cannot modify the entity list during iteration.


```lua
local ents = ents.FindInSphere(ply:GetPos(), 512)
```

Reason: FindInSphere uses the engine's spatial hash grid (not PVS culling), so it skips the frustum and visibility overhead of FindInPVS while still being O(1) amortized for lookup — just a hash to the grid cell + range check.


```lua
local function GetPlayersNear(pos, radiusSqr)
    local result = {}
    for _, pl in ipairs(player.GetAll()) do
        if pl:GetPos():DistToSqr(pos) <= radiusSqr then
            result[#result + 1] = pl
        end
    end
    return result
end
```

Reason: `player.GetAll()` iterates over the player list only (tens to low hundreds), while `ents.FindInSphere` traverses all world entities (potentially thousands including props, ragdolls, NPCs, and effects). The squared-distance check avoids the expensive `sqrt()` in every comparison.


```lua
for i = 1, n do end
```
Reason: The numeric `for` loop compiles to a single specialized `FORLOOP` VM opcode that handles comparison and increment internally, while `while` generates separate bytecodes for the comparison, increment, and jump, making `for` measurably faster in the tight loop case.


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

```lua
-- Slower: looping and calling hook.Run per player
for _, ply in ipairs(player.GetHumans()) do
    hook.Run("TickNotify", ply)
end
```

Reason: hook.Run performs table lookups and function dispatch overhead per invocation; batching all players into one call eliminates N-1 of those overhead cycles per tick.


```lua
local ply = LocalPlayer()
local health = ply:Health()
draw.SimpleText(health, "DermaLarge", 10, 10)
draw.SimpleText(health, "DermaLarge", 10, 40)
draw.SimpleText(health, "DermaLarge", 10, 70)
```

Reason: `LocalPlayer():Health()` crosses the Lua-C boundary and reads a networked variable; caching it once per frame eliminates two redundant crossings that return the same value within a single frame.


```lua
local clrWhite = Color(255, 255, 255)
-- then use clrWhite in the loop instead of Color(255,255,255)
```
Reason: Color() allocates a new table each call; hoisting it outside the loop avoids per-frame GC pressure and table allocation.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```

Reason: Localizing the function avoids a global table lookup (`_G.math`) and a method table lookup (`math.sin`) on every iteration, replacing two hash lookups with one upvalue access.


```lua
local ply = LocalPlayer()
-- use ply instead of LocalPlayer() throughout
```
Reason: LocalPlayer() is a C API call through the Lua interface with lookup overhead; caching it in a local variable avoids the C boundary lookup on every reference.


```lua
function PlayersLookingAtEachOther(ply1, ply2, threshold)
  threshold = threshold or 0.95
  local dir1 = ply1:GetAimVector()
  local dir2 = ply2:GetAimVector()
  local to2 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
  local to1 = -to2
  return dir1:Dot(to2) > threshold and dir2:Dot(to1) > threshold
end
```
Reason: Dot products against the normalized delta vector replace `math.acos` with two scalar comparisons and one negation — the threshold corresponds directly to a cosine cone width, so the "roughly" tolerance is a single tunable number with no trig calls, no `Clamp`, and no edge-case division.


```lua
SomeHelper(ply)
```
Reason: `ply:SomeHelper()` triggers GMod's metatable method lookup on the entity, while `SomeHelper(ply)` with a localized function is a direct call — no metatable traversal.


```lua
-- Slow: print("debug value:", val)
-- Fast:
MsgN("debug value: ", val)
```
Reason: `print()` formats arguments through `tostring`, appends timestamps, and serializes output over the network for multiplayer clients, while `MsgN()` writes directly to the server console with zero overhead.


```lua
for i = 1, #t do
  local v = t[i]
end
```
Reason: Numeric for avoids per-iteration iterator function calls and hash lookups that pairs and ipairs require; in GMod's LuaJIT this compiles to a tight bytecode/hot-loop trace with raw array access.


```lua
-- fn approach (slower)
local result = fn.Compose(
  fn.Map(fn.Sum(10)),
  fn.Filter(fn.IsEven)
)(nums)

-- plain loop (faster)
local result = {}
for i = 1, #nums do
  local v = nums[i]
  if v % 2 == 0 then
    result[#result + 1] = v + 10
  end
end
```
Reason: `fn` chains allocate a closure per combinator per call and traverse the table once per stage; a single `for` loop does filter+map in one pass with zero closures, and LuaJIT compiles the tight loop to native code while per-element C function calls (via `fn.Curry` wrappers) remain interpreted call overhead that cannot be JIT-compiled away.


```lua
local plyCache = {}

hook.Add("PlayerInitialSpawn", "CachePlayers", function() plyCache = player.GetAll() end)
hook.Add("PlayerDisconnected", "CachePlayers", function() plyCache = player.GetAll() end)
plyCache = player.GetAll() -- initial fill

hook.Add("Tick", "UseCachedPlayers", function()
    for i, ply in ipairs(plyCache) do
        -- per-tick work, no GetAll call
    end
end)
```
Reason: `player.GetAll()` allocates a new table every call; caching it and refreshing only on join/leave (two events that are rare relative to ticks) eliminates 66+ heap allocations per second and the O(n) copy of the player pointer array on every tick.


```lua
local pdata = setmetatable({}, {__mode = "k"})
-- write: pdata[ply] = value
-- read:  pdata[ply]
```
Reason: Direct Lua-table lookup with the player userdata as key avoids the string-key and metatable overhead of `ply[key]`, which in GMod traverses the entity's C metatable chain on every read.


```lua
-- Sequential number-indexed array (fast)
local items = {"a", "b", "c"}
for i = 1, #items do
    local v = items[i]
end

-- String-keyed map (slower)
local items = {a = 1, b = 2, c = 3}
for k, v in pairs(items) do
end
```

Reason: Numerical `for` loops over sequentially-indexed arrays leverage the array part of Lua tables with direct memory access and no hashing overhead, while `pairs` over string-keyed tables must compute hash lookups for each key and yields iterator function calls, making the array form consistently faster in Garry's Mod Lua.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Creating a Color object allocates a table and sets up metatables, while passing raw numbers avoids allocation entirely, reducing GC pressure in hot draw paths.


```lua
local result = sql.Query("SELECT * FROM gmod_player_data WHERE steamid = " .. SQLStr(playerSteamID64))
```

Reason: SQLite runs in-process with no network round-trip, while remote MySQL requires TCP/IP connection overhead — for a single-server setup, SQLite's local I/O is strictly lower latency.


```lua
local steamid_cache = setmetatable({}, {__mode = "k"})
function GetSteamID(ply)
    local id = steamid_cache[ply]
    if not id then
        id = ply:SteamID()
        steamid_cache[ply] = id
    end
    return id
end
```
Reason: `ply:SteamID()` calls into the C layer and formats a string on every invocation; a weak-keyed table caches the result per player object with O(1) lookup and allows garbage collection when players disconnect.


```lua
-- Slow: repeated .. concatenation (O(n^2))
local str = ""
for i = 1, 10000 do
    str = str .. tostring(i)
end

-- Fast: table.concat (O(n))
local parts = {}
for i = 1, 10000 do
    parts[i] = tostring(i)
end
local str = table.concat(parts)
```
Reason: Every `..` allocates a new string and copies both operands, giving O(n^2) total copies. `table.concat` precomputes the final size, allocates once, and writes each fragment directly into the buffer — O(n).


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```

Reason: `draw.RoundedBox` always checks and processes the radius parameter even when it's 0, adding function call overhead; `surface.DrawRect` is the raw paint surface call with no branching, no rounding math, and one fewer Lua function boundary.


```lua
surface.SetFont("MyFont")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 10)
surface.DrawText("Hello world")
```
Reason: surface.* helpers call into the engine's native text path directly without the Lua wrapper overhead of draw.DrawText or the double-pass outline rendering of SimpleTextOutlined.


```lua
#t
```

Reason: The `#` operator is the idiomatic and fastest way to get the length of a sequential array-like table in Lua, functioning in O(log n) due to the internal table representation, and is preferred over `table.Count` or manual iteration in Garry's Mod for flat sequences with no gaps.


```lua
t = {}
```
Reason: `t = {}` is O(1) — it allocates a new empty table and reassigns the local, deferring the old table's cleanup to the GC. `table.Empty(t)` is O(n) because it must iterate over every element to clear it in C, and the table's underlying array capacity is never reclaimed, making `t = {}` strictly faster for large sequential tables.


```lua
local set = { ["some_key"] = true }
if set["some_key"] then
    -- exists
end
```

Reason: table.HasValue iterates the entire list O(n) on every check, while a set lookup is O(1) hash-table access — the difference grows linearly with list size.


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

Reason: Table constructor with literal fields compiles to a single `NEWTABLE` + `SETLIST` sequence in one instruction stream, whereas assigning fields after `{}` generates one `NEWTABLE` plus a separate `SETTABLE` opcode per field, each incurring hash-lookup cost.


```lua
return t[math.random(#t)]
```
Reason: table.Random is a general-purpose function that handles both sequential and key-value tables with extra overhead for type detection and key collection, while math.random with the length operator directly indexes a sequential table in O(1) with minimal Lua/C boundary calls.


```lua
x * x
```
Reason: Multiplication avoids the __pow metamethod lookup and function call overhead of `^` or `math.pow`, and LuaJIT (which GMod uses) can JIT it to a single machine instruction.


```lua
for _, v in ipairs(player.GetAll()) do
    -- v is a Player object
end
```
Reason: `player.GetAll()` returns a sequential array (indices 1..N), so `ipairs` is more correct than `pairs` — it guarantees ordered iteration over only the integer keys and avoids any non-sequential table overhead.


```lua
for _, ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```

Reason: `ents.Iterator()` is a true lazy iterator that yields entities one at a time, so it never constructs a table of every entity; a class filter selects only prop_physics.


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

Reason: `hook.Add` registers a callback under a named identifier on the given hook, so passing `"Think"` and `"MyAddon.Think"` attaches the function to the Think hook with that identifier.


```lua
if IsValid(ent) then
    -- safe to call ent:SomeMethod() here
end
```

Reason: `IsValid(ent)` returns false if `ent` is nil, already removed from the game, or otherwise invalid, so it guards against calling methods on a dead or null entity reference.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadString()
    -- handle the incoming data here
end)
```

Reason: `net.Receive` registers a callback on the client (or server, for client->server messages) that runs whenever a net message with the given name is received, passing the message length and, on the server, the sending player.


```lua
local ang = Angle()

local function getZeroAngle()
    ang.p = 0
    ang.y = 0
    ang.r = 0
    return ang
end
```

Reason: Reusing one preallocated Angle and zeroing its pitch/yaw/roll avoids the per-call allocation and GC pressure of `Angle()` in the hot path.


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

local r = color.r
```

Reason: Flat locals avoid per-access hash lookups (table indexing is slower than register/local access), so a local copy of the setting read in hot code paths is fastest.


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

Reason: `getDarkRPVar("job")` is DarkRP's intended accessor for server-set job data and avoids the brittle, untyped network-string access that `GetNWString("job")` relies on.


```lua
if (a:DistToSqr(b) < threshold * threshold) then
    -- closer than threshold units
end
```

Reason: `DistToSqr` compares squared distance, avoiding the costly sqrt from `Distance`, and is the idiomatic GMod threshold check.


```lua
for _, ent in ents.Iterator() do
    -- visit each entity
end
```

Reason: `ents.Iterator()` is the GMod wiki-recommended efficient iterator because it yields entities lazily without allocating a table, unlike `ents.GetAll()`.


```lua
local ply = Entity(1)
local center = ply:GetPos()
local radius = 256
local found = ents.FindInSphere(center, radius)
for _, ent in ipairs(found) do
    if ent ~= ply and ent:IsValid() then
        -- do cheap work with nearby entity
    end
end
```

Reason: `ents.FindInSphere` is a common benchmark-fast built-in spatial query that returns entities within a radius in one C-side pass, cheaper than PVS-based lookups for small local neighborhoods.


```lua
local function FindPlayersInRadius(pos, radius)
    local r2 = radius * radius
    local found = {}
    for _, ply in ipairs(player.GetAll()) do
        if IsValid(ply) and pos:DistToSqr(ply:GetPos()) <= r2 then
            found[#found + 1] = ply
        end
    end
    return found
end
```

Reason: player.GetAll() returns only connected players (a short list), so iterating and testing squared distance avoids ents.FindInSphere's costly broad-phase scan over every entity in the world.


```lua
for i = 1, n do
  -- body
end
```

Reason: numeric `for` loops are compiled to a single opcode that caches the limit/step once, avoiding per-iteration comparisons and index arithmetic, so they run faster than an equivalent `while` loop in Garry's Mod's Lua VM.


```lua
-- Slower: per-player hook.Call overhead every iteration
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTick", ply)
end

-- Faster: single hook.Call; receivers iterate the passed player list
hook.Run("MyTick", player.GetAll())
```

Reason: `hook.Run`/`hook.Call` does a table lookup and hook iteration on every call, so one call with all players amortizes that fixed overhead instead of paying it per player.


```lua
local ply = LocalPlayer()
local hp = ply:Health()
draw.SimpleText(hp, "HUDNum", 10, 10)
draw.SimpleTextOutlined(hp, "HUDNum", 10, 40, color_white, 1, 1)
surface.SetDrawColor(255 - hp * 2.55, hp * 2.55, 0)
surface.DrawRect(10, 70, 200, 10)
```

Reason: Cache LocalPlayer() and Health() once per frame instead of calling each three times, avoiding repeated table lookups and function calls.


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

function PANEL:Paint(w, h)
    draw.RoundedBox(0, 0, 0, w, h, WHITE)
end
```
Reason: Color() allocates a new table every call, so caching it once as an upvalue avoids per-frame table churn and GC pressure in the paint loop.


```lua
local sin = math.sin
for i = 1, 1e6 do
    local y = sin(i)
end
```

Reason: Localizing `math.sin` into a local variable avoids the repeated global->table lookup (`math.sin`) on every iteration, replacing it with a single upvalue/local access which is faster in Lua's virtual machine.


```lua
local ply = LocalPlayer()

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

hook.Add("PlayerSpawn", "refresh_localplayer", function(p)
    if p == ply or p:IsPlayer() and p == LocalPlayer() then
        ply = p
    end
end)

-- use `ply` instead of calling LocalPlayer() repeatedly
```

Reason: Caching LocalPlayer() in a local variable avoids the per-call table lookup/traversal, and the hooks refresh it only when the local player entity changes (respawn/initial spawn).


```lua
local function lookingAtEachOther(a, b, thresh)
    thresh = thresh or 0.5 -- ~60 degrees cone
    local dirAB = (b:GetPos() - a:GetPos()):GetNormalized()
    local dirBA = -dirAB
    return a:GetAimVector():Dot(dirAB) > thresh
       and b:GetAimVector():Dot(dirBA) > thresh
end
```

Reason: Dot products of each player's aim vector against the normalized direction to the other replace angle math.acos with a single cheap multiply-add, flagging mutual facing when both exceed a cosine threshold.


```lua
SomeHelper(ply)
```

Reason: `ply:SomeHelper()` does an extra metatable/table index to resolve the method before calling it with `self`, whereas `SomeHelper(ply)` is a direct global call with no lookup overhead.


```lua
MsgN("debug value: ", value)
```

Reason: `MsgN` writes directly to the console without `print`'s per-arg `tostring` joining and tab-separator overhead, making it cheaper in a hot path.


```lua
for i = 1, #t do
    local v = t[i]
end
```

Reason: Numeric `for` with `#t` and direct indexing avoids per-iteration function calls and hash lookups, making it faster than `ipairs` (iterator/call overhead) and far faster than `pairs` (non-sequential hash traversal, no early stop).


```lua
-- DarkRP fn version (slow: coroutines, closures, multiple passes)
-- local rich = fn.Filter(function(p) return p:getDarkRPVar("money") > 1000 end)(players)
-- local names = fn.Map(function(p) return p:Nick() end)(rich)

-- Faster: one plain loop, no fn combinator overhead
local function richNames(players)
    local out = {}
    for i = 1, #players do
        local p = players[i]
        if p:getDarkRPVar("money") > 1000 then
            out[#out + 1] = p:Nick()
        end
    end
    return out
end
```

Reason: A single plain `for` loop avoids fn's coroutine/closure allocation and multiple passes, doing filter+map in one iteration.


```lua
local g_Players = {}

local function refresh()
    local t = {}
    for _, ply in ipairs(player.GetAll()) do
        t[#t + 1] = ply
    end
    g_Players = t
end

hook.Add("PlayerConnect", "cache.players", refresh)
hook.Add("PlayerDisconnected", "cache.players", refresh)
hook.Add("PlayerSpawn", "cache.players", function(ply)
    if ply:IsBot() then refresh() end -- bots may not fire Connect reliably
end)

refresh()

hook.Add("Tick", "use.cached.players", function()
    for i = 1, #g_Players do
        local ply = g_Players[i]
        if IsValid(ply) then
            -- do per-player work here
        end
    end
end)
```

Reason: Cache the player list in a module-local table, rebuild it only on join/leave/disconnect hooks, and iterate the cached array by index each tick instead of calling `player.GetAll()` (which allocates a new table).


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

local function set(ply, k, v)
    local t = PlayerTemp[ply]
    if not t then t = {}; PlayerTemp[ply] = t end
    t[k] = v
end

-- hot read path: cache the field itself in a local, not the player
local value = PlayerTemp[ply].someField
```

Reason: Reading a Lua table field is a hash lookup per access; binding it once to a local variable (or caching the inner table in a local) removes repeated key indexing in hot loops, and the weak-keyed table lets disconnected players be collected automatically.


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

Reason: Sequential numeric arrays avoid the hash lookup and key enumeration overhead of pairs on string-keyed maps, so numeric `#`-bounded iteration is faster in Garry's Mod Lua.


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

Reason: Passing r,g,b,a as separate numbers avoids allocating a new Color table every call, which matters on a hot draw path where surface.SetDrawColor runs each frame.


```lua
local db = sql.Open("playerdata")
local row = sql.Query("SELECT score FROM players WHERE steamid = " .. sql.SQLStr(ply:SteamID()))
if row then
    print(row[1].score)
end
sql.Query("UPDATE players SET score = 100 WHERE steamid = " .. sql.SQLStr(ply:SteamID()))
```

Reason: Local SQLite avoids network round-trips to a remote MySQL server, so reads/writes are lower latency for a single server with no multi-server sync need.


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

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

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

Reason: SteamID() rebuilds the string via bit operations on every call; a weak-keyed table memoizes the result per player object (no string recompute on the hot path) while letting disconnected players be garbage-collected.


```lua
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece " .. i .. "\n"
end
local result = table.concat(parts)
```

Reason: Repeated `..` concatenation is O(n²) because Lua reallocates and copies the whole string each time; buffering pieces in a table and calling `table.concat` copies each byte once, making it O(n).


```lua
local x, y, w, h = 10, 10, 100, 50
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(x, y, w, h)
```

Reason: `surface.DrawRect` skips the rounded-corner/texture setup that `draw.RoundedBox(0, ...)` still performs, so it issues a plain filled-rect draw with less overhead per call.


```lua
-- Cache the font once, then draw with the low-level surface.* path every frame.
-- Avoid draw.DrawText / draw.SimpleTextOutlined in RT hot paths.

local TEXT   = "Hello, world"
local FONT   = "DermaDefault"
local COL    = Color(255, 255, 255)

hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(FONT)                 -- set once per draw
    surface.SetTextColor(COL.r, COL.g, COL.b, COL.a)  -- ints, no Color parsing
    surface.SetTextPos(20, 20)            -- integer coords, no alignment math
    surface.DrawText(TEXT)
end)
```
Reason: draw.DrawText/SimpleTextOutlined internally call surface.SetFont plus string.Explode/alignment measuring (and SimpleTextOutlined draws the text 5x for the outline), so calling surface.SetFont/SetTextColor/SetTextPos/DrawText directly skips that per-frame parsing overhead for a single line.


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

Reason: In Garry's Mod Lua (Lua 5.1/LuaJIT), the `#` length operator is the idiomatic, fastest way to get the length of a sequential array-like table, whereas `table.Count` is for associative tables and is slower.


```lua
t = {}
```

Reason: Assigning a new empty table is O(1) and lets the GC reclaim the old table, whereas table.Empty iterates and nils every key individually, making it O(n) for a large table.


```lua
-- table.HasValue is O(n): scans every entry each call
local list = { "a", "b", "c", "d" }
if table.HasValue(list, "c") then print("found") end

-- Faster: invert into a lookup set once, then O(1) membership tests
local set = {}
for _, v in ipairs(list) do set[v] = true end
if set["c"] then print("found") end
```

Reason: table.HasValue does a linear O(n) scan per lookup, while a hash-set built once gives O(1) membership checks thereafter.


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

Reason: The table constructor pre-sizes the hash part and sets fields in one allocation, avoiding repeated hash lookups and rehashing from post-creation assignment.


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

Reason: table.Random iterates the whole table to count its length first, whereas indexing with `t[math.random(#t)]` uses the O(1) `#` length operator and a single random index lookup.


```lua
local x = x
for i = 1, n do
    local s = x * x
    x = s
end
```

Reason: `x * x` compiles to a single float-multiply in LuaJIT, while `x^2` lowers to a slower `pow`/`math.pow` call; localizing keeps the value in a register.


```lua
for _, ply in player.Iterator() do
    -- ply is each connected player
end
```

Reason: `player.Iterator()` is the modern, allocation-free replacement for `pairs(player.GetAll())` and avoids building a temporary table, making it the recommended way to loop over connected players in current GMod.


```lua
for _, ent in ents.Iterator({ ClassName = "prop_physics" }) do
    -- ent is a prop_physics; do work here
end
```

Reason: `ents.Iterator` lazily yields only matching entities via an internal C-side walk, so it visits every `prop_physics` without materializing a full entity table first.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```

Reason: `hook.Add("Think", "MyAddon.Think", fn)` registers the function to run every frame on the Think hook under the unique identifier MyAddon.Think.


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

Reason: `IsValid()` returns false for nil, removed, or invalid entities, preventing errors from calling methods on a dead reference.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadString()
    -- handle the received data here
end)
```

Reason: `net.Receive` registers a callback that runs on the client (or server) whenever a net message with the given name is received.


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

-- Hot path: clone a cached zeroed angle instead of calling Angle() each time
local a = ZERO_ANGLE:Clone()
```

Reason: Cloning a cached Angle avoids the C-side constructor/allocation cost of `Angle()` on every call; even faster is reusing one Angle and calling `:Zero()` in place to skip allocation entirely.


```lua
local myColor = Color(255, 0, 0)
local r = myColor.r
```

Reason: Lua local variables are accessed by register with no hash lookup, so reading a flat local is faster than repeated nested table indexing (myaddon.config.color) which performs multiple hash lookups per access.


```lua
-- Preferred: use the DarkRP team/job API
local job = ply:getDarkRPVar("job")

-- Avoid: reading the raw networked string directly
-- local job = ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` is DarkRP's official accessor that reads the job name from its managed networked var table, staying correct across job changes and internal representation shifts, whereas `GetNWString("job")` relies on an undocumented networking key DarkRP does not guarantee.


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

Reason: `DistToSqr` compares squared distances, avoiding the `sqrt` cost of `Distance` while giving an exact threshold check.


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
    print(ent)
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator over all entities, avoiding the table copy that `ents.GetAll()` creates.


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
for _, ent in ipairs(nearby) do
    if ent ~= player and ent:IsValid() then
        -- cheap spatial query result
    end
end
```

Reason: ents.FindInSphere is a widely benchmarked, engine-side radius query that is faster than FindInPVS for a simple nearby-entity lookup and avoids PVS visibility overhead.


```lua
local function PlayersInRadius(pos, radius)
    local result = {}
    local r2 = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= r2 then
            result[#result + 1] = ply
        end
    end
    return result
end
```

Reason: player.GetAll() only iterates the (far smaller) player list and uses squared-distance comparison to avoid a sqrt, skipping the broad ents.FindInSphere scan over every entity.


```lua
for i = 1, n do
  -- body
end
```

Reason: Lua's numeric `for` precomputes the limit once and is compiled to a single optimized VM opcode, avoiding per-iteration limit re-evaluation and index arithmetic that a `while` loop performs.


```lua
local players = player.GetAll()
hook.Run("TickPlayers", players)
```

Reason: One `hook.Run` call amortizes the hook-table lookup, closure iteration, and argument packing across all players instead of paying that overhead N times per tick.


```lua
local ply = LocalPlayer()
local hp = ply:Health()
draw.SimpleText(hp, "HUDHealth", 10, 10)
draw.SimpleText(hp * 0.5, "HUDHealth", 10, 40)
draw.RoundedBox(4, 10, 70, hp, 16, Color(200, 40, 40))
```

Reason: LocalPlayer():Health() is a C++ round-trip each call; calling it once per frame and caching the result eliminates two redundant native calls in the hot HUDPaint path.


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

hook.Add("HUDPaint", "ExamplePaint", function()
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 64, 64)
end)
```

Reason: Allocating a new Color table every iteration is the bottleneck, so build it once outside the loop and reuse the same reference.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local v = sin(i)
end
```

Reason: Localizing `math.sin` into a local avoids a repeated global/table lookup on every iteration of the hot loop.


```lua
local ply = LocalPlayer()

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

hook.Add("PlayerSpawn", "cache_localplayer", function(p)
    if p == ply then return end
end)

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

Reason: LocalPlayer() walks the entity list each call; storing it in a local and only re-resolving on invalidation (InitPostEntity/ClientInit) avoids the per-call lookup while staying safe across respawns.


```lua
local dirA = plyA:GetAimVector()
local dirB = plyB:GetAimVector()
local toB = (plyB:GetPos() - plyA:GetPos()):GetNormalized()
local toA = (plyA:GetPos() - plyB:GetPos()):GetNormalized()
local cosLimit = 0.5 -- ~60deg cone
if dirA:Dot(toB) > cosLimit and dirB:Dot(toA) > cosLimit then
    -- players are roughly looking at each other
end
```

Reason: Dot product of normalized vectors equals cos(angle); comparing against a threshold avoids `math.acos` and gives a cheap direction-cone test.


```lua
SomeHelper(ply)
```
Reason: `ply:SomeHelper()` triggers a metatable `__index` lookup to resolve the method, while `SomeHelper(ply)` is a single global resolve—marginally faster for helpers you control, with no real ergonomic loss.


```lua
MsgN("debug: value = ", value)
```

Reason: `MsgN` skips `print`'s per-argument type detection and formatting overhead, writing raw values straight to the console, which is faster in hot paths.


```lua
local n = #t
for i = 1, n do
    local v = t[i]
end
```

Reason: Numeric for with a cached length avoids the per-iteration function call and key hashing of ipairs/pairs, making it the fastest typical iteration over a dense array-like table.


```lua
-- DarkRP's fn library builds combinators (fn.curry, fp.compose, map/filter as HOFs)
-- that allocate closures/tables per stage and iterate the list multiple times.
-- Faster: one plain loop, one output table, no closures, no intermediate lists.

-- Example: from all players, keep alive humans, collect {ply, name, money} for cops.
local function buildCopReport(players)
    local out = {}
    local n = 0
    for i = 1, #players do
        local ply = players[i]
        if ply:Alive() and ply:Team() == TEAM_POLICE then
            n = n + 1
            out[n] = {
                ply   = ply,
                name  = ply:Nick(),
                money = ply:getDarkRPVar("money"),
            }
        end
    end
    return out
end

-- Reusable generic single-pass filter+map (no per-stage closures beyond the two passed):
local function filterMap(t, keep, transform)
    local out, n = {}, 0
    for i = 1, #t do
        local v = t[i]
        if keep(v) then
            n = n + 1
            out[n] = transform(v)
        end
    end
    return out
end
```
Reason: A single manual loop fuses filter+map into one pass with one output table and zero per-element combinator closures, avoiding fn's repeated iteration, intermediate tables, and closure allocation that dominate cost in Lua's hot paths.


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

gameevent.Listen("player_connect")
hook.Add("PlayerConnect", "cache_players", function()
    players = player.GetAll()
end)

gameevent.Listen("player_disconnect")
hook.Add("PlayerDisconnect", "cache_players", function()
    players = player.GetAll()
end)

hook.Add("Think", "use_cached_players", function()
    for i = 1, #players do
        local ply = players[i]
        -- do work with ply
    end
end)
```

Reason: Cache player.GetAll() once and rebuild it only on PlayerConnect/PlayerDisconnect, so the hot Think loop iterates a plain array instead of calling ipairs on a freshly built table every tick.


```lua
local pdata = {} -- integer-indexed (array part) = faster than string-hashed entity fields

local function SetTemp(ply, val)
    pdata[ply:EntIndex()] = val
end

local function HotRead(ply)
    local v = pdata[ply:EntIndex()] -- integer key lookup, then cache in local `v`
    return v
end
```

Reason: An integer-keyed plain table hits Lua's fast array part instead of the hashed string lookup used for `ply.someField` on the entity userdata, and reading into a `local` avoids repeated table access on hot paths.


```lua
local items = { "alpha", "beta", "gamma", "delta" }
for i = 1, #items do
    local v = items[i]
    -- v is the value; i is the sequential index
end
```

Reason: Sequential integer-indexed arrays iterate in O(n) with no hash lookups via numeric `for`/`ipairs`, whereas string-keyed maps force O(n) hash-based `pairs` traversal with no length or guaranteed order, making the array shape faster and cache-friendlier in Garry's Mod Lua.


```lua
surface.SetDrawColor(r, g, b, a)
```

Reason: Passing separate numbers avoids allocating a new Color table every frame, removing per-call GC pressure on the hot draw path.


```lua
local db = sql.Open("playerdata")
local name = db:query("SELECT name FROM players WHERE steamid = " .. sql.SQLStr(steamid)):GetRow().name
```

Reason: Local SQLite avoids network round-trips to a remote host, so reads/writes have lower and more predictable latency for single-server storage.


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

gameevent.Listen("player_disconnect")
hook.Add("player_disconnect", "ClearSteamIDCache", function(data)
    local ply = Player(data.userid)
    if IsValid(ply) then steamIDCache[ply] = nil end
end)
```

Reason: SteamID() rebuilds a string each call; caching on the player key with a weak table avoids repeated work and self-clears on disconnect.


```lua
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece " .. i .. "\n"
end
local result = table.concat(parts)
```

Reason: Lua strings are immutable, so repeated `..` concatenation copies the whole growing string each time (O(n²)); buffering pieces in a table and joining once with `table.concat` is O(n).


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` skips the corner-radius branching, color table unpacking, and extra function overhead that `draw.RoundedBox` incurs, so it draws a plain filled rect with less per-call work.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
hook.Add("HUDPaint", "fastSingleLine", function()
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello, world")
end)
```

Reason: surface.DrawText reuses a pre-set font and color and skips the size/color/markup parsing that draw.DrawText and draw.SimpleText perform each call, so only SetTextPos+DrawText run per frame.


```lua
local len = #myTable
```

Reason: In Lua (and GMod Lua), the unary length operator `#` is the preferred, fastest way to get the length of a sequential array-like table; `table.Count` is for non-sequential/associative tables.


```lua
local t = { ... } -- large sequential table
t = {}            -- reassign to a fresh empty table; O(1), old table is GC'd
```

Reason: `t = {}` is O(1) — it just drops the reference and lets the GC reclaim the old table, whereas `table.Empty(t)` walks every entry to nil it out (O(n)), so the reassignment is generally faster for large tables.


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

if set[value] then
    -- value exists
end
```

Reason: table.HasValue does a linear O(n) scan on every check, while building a hash set once gives O(1) membership lookups.


```lua
-- Faster: fields in the constructor (single allocation, no rehash)
local t = { x = 1, y = 2, z = 3 }

-- Slower: separate assignments trigger multiple rehashes
local t = {}
t.x = 1
t.y = 2
t.z = 3
```
Reason: The constructor allocates the table at its final size in one step, while post-`{}` assignments force the hash part to grow and rehash repeatedly.


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

Reason: table.Random iterates the entire table to count entries, while indexing by `math.random(#t)` is O(1) and avoids the full traversal.


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

Reason: `x * x` avoids the `^` operator's `math.pow` call and is faster in a tight loop.


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

Reason: `player.GetAll()` returns a sequential array of connected players, so `ipairs` iterates them in order with the player object directly as `ply`.


```lua
for _, ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- process ent here
    end
end
```

Reason: `ents.Iterator()` walks the engine's entity list lazily and yields one entity at a time, so no table of all map entities is ever constructed (unlike `ents.GetAll()`), while still visiting every `prop_physics`.


```lua
hook.Add("Think", "MyAddon.Think", function()
	-- callback body
end)
```

Reason: `hook.Add` registers a callback under the unique identifier `MyAddon.Think` on the `Think` game hook.


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

Reason: `IsValid` returns false for nil, entities marked for removal, or the NULL entity, preventing calls on stale references that would error or misbehave.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming message: read data with net.Read* and use ply (server side)
end)
```

Reason: `net.Receive` registers a callback that runs when a net message with the given name arrives, receiving the bit length and (on the server) the sending player.


```lua
local zeroAngle = Angle(0, 0, 0)
local function getZeroAngle()
    zeroAngle:Zero()
    return zeroAngle
end
```

Reason: Reusing a single Angle and calling `:Zero()` avoids per-call allocation in the hot path, unlike `Angle()` which constructs a new object each time.


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

local c = color
```

Reason: A local variable resolves via a single register/upvalue lookup, while myaddon.config.color requires multiple chained hash-table lookups on each read, making the flat local faster for frequent access.


```lua
ply:getDarkRPVar("job")
```

Reason: `getDarkRPVar` reads the networked DarkRP variable through the intended abstraction instead of reaching into the raw NWString, avoiding magic-string coupling to the network layer and staying consistent with DarkRP's API.


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

Reason: `DistToSqr` compares squared distances and avoids the costly square-root of `Distance`, so a threshold check only needs to square the threshold once.


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

Reason: The GMod wiki recommends `ents.Iterator()` over `ents.GetAll()` because it is a generator-based for-loop iterator that avoids allocating a full table of every entity, making it more memory- and performance-efficient when visiting all entities.


```lua
local nearby = ents.FindInSphere(player:GetPos(), 256)
for _, ent in ipairs(nearby) do
    if ent ~= player and ent:IsValid() then
        -- process entity
    end
end
```

Reason: ents.FindInSphere is a cheap native sphere query that avoids PVS/engine visibility cost and is consistently faster than FindInBox/FindInPVS for proximity checks in common GMod benchmarks.


```lua
local function PlayersInRadius(pos, radius)
    local r2 = radius * radius
    local found = {}
    for i = 1, player.GetCount() do
        local ply = player.Get(i)
        if ply and IsValid(ply) then
            local d = ply:GetPos() - pos
            if d:LengthSqr() <= r2 then
                found[#found + 1] = ply
            end
        end
    end
    return found
end
```
Reason: Iterating only the (small) player list with squared-distance checks avoids ents.FindInSphere's full entity scan and per-entity player test, so it scales with player count instead of total entity count.


```lua
for i = 1, n do
    -- body
end
```

Reason: A numeric `for` evaluates the limit and step once and uses a fast internal counter, whereas `while` re-checks the condition and increments the index each iteration, making `for` generally faster in Lua.


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

-- Slower: N hook calls, one per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("TickPlayers", ply)
end
```

Reason: hook.Run has fixed per-call overhead (table lookup, arg packing, iteration over hooks); batching all players into a single call does that work once instead of once per player, so cost scales with hook count, not player count.