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

Reason: `ents.Iterator()` yields each entity one at a time via an iterator function, so no intermediate table is allocated — the class check is applied inline per entity.


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

Reason: `hook.Add(hookName, identifier, func)` registers a callback; `"Think"` fires every frame and `"MyAddon.Think"` is the unique ID to prevent duplicates.


Uses IsValid for entity/object validity.

```lua
if not IsValid(ent) then return end
```

Reason: `IsValid` returns `false` for NULL/removed entities before you index or method-call on them, preventing script errors.


```lua
net.Receive("MyAddon.Sync", function(len)
  -- handle the incoming message here
end)
```

Reason: `net.Receive` is the Garry's Mod Lua API for registering a callback that fires when a named net message arrives from the server or client.


Answer must begin its reason with Reason:

```lua
-- Reuse a pre-zeroed sentinel instead of constructing Angle(0,0,0) every call
local ANGLE_ZERO = Angle(0, 0, 0)

-- In the hot path:
local ang = ANGLE_ZERO -- cheap reference copy; do NOT mutate this
-- or if you need a mutable clone for local tweaks:
local ang = ANGLE_ZERO --[[ reuse pattern: just read from it ]]

-- Constructing a new Angle() each frame allocates and GCs needlessly.
-- Storing a local copy avoids the per-call allocation:
local ang = ANGLE_ZERO
ang.p, ang.y, ang.r = 0, 0, 0 -- reset if you must mutate

-- Fastest idiom for "I need a zeroed Angle right now":
local ang = Angle() -- engine may pool; still heavier than reuse
-- vs:
local ang = ANGLE_ZERO -- single upvalue read, zero GC pressure
```

**Reason:** `Angle()` allocates a new userdata on the Lua heap every call, creating GC pressure; a module-scope `local ANGLE_ZERO = Angle(0,0,0)` is a single cheap upvalue read with zero allocation cost, making it significantly faster in hot paths.


```lua
local myColor = myaddon.config.color
print(myColor)
```
Reason: local variable lookup is faster than repeated table indexing.


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

Reason: `ply:getDarkRPVar("job")` is the canonical DarkRP API that reads the server-synchronized job name, while `ply:GetNWString("job")` depends on an internal NW string key that may be unset, overridden, or break across DarkRP versions.


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

`Vector:DistToSqr(other)` is preferred over `Vector:Distance(other)` because it avoids the `sqrt` call. Square your threshold and compare.

```lua
local function isWithinThreshold(a, b, threshold)
  return a:DistToSqr(b) < threshold * threshold
end
```

Reason: `DistToSqr` avoids an unnecessary square root, which is the idiomatic GMod approach for threshold checks.


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

Reason: `ents.GetAll()` returns a pre-built array, avoiding the overhead of `ipairs(ents.FindByClass("*"))` or repeated `Entity(i)` calls, and is the wiki-recommended approach for iterating every entity.


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

Reason: Ents.FindInSphere uses a simple spatial hash lookup in the engine with early-out bounding sphere culling and avoids PVS/camera state dependency, making it consistently faster than FindInBox or FindByClass for small-radius queries.


Answer must contain 0 through 2 candidate loops.

```lua
-- Fast radius player lookup: spatial hash with 64-unit cells
-- Call once per think; reuse the table across calls to avoid GC.
local CELL = 64
local bucketCache = {} -- reuse across frames, clear entries not entire table

local function BuildPlayerGrid(players)
    table.Empty(bucketCache)
    for i = 1, #players do
        local p = players[i]
        if p:Alive() then
            local pos = p:GetPos()
            local cx = math.floor(pos.x / CELL)
            local cy = math.floor(pos.y / CELL)
            local key = cx * 73856093 + cy * 19349663 -- spatial hash key
            local b = bucketCache[key]
            if not b then
                b = {}
                bucketCache[key] = b
            end
            b[#b + 1] = p
        end
    end
    return bucketCache
end

local function PlayersNear(pos, radius, players)
    local grid = BuildPlayerGrid(players)
    local result = {}
    local r2 = radius * radius
    local cr = math.ceil(radius / CELL)
    local cx = math.floor(pos.x / CELL)
    local cy = math.floor(pos.y / CELL)

    for dx = -cr, cr do
        for dy = -cr, cr do
            local key = (cx + dx) * 73856093 + (cy + dy) * 19349663
            local bucket = grid[key]
            if bucket then
                for i = 1, #bucket do
                    local p = bucket[i]
                    local diff = p:GetPos() - pos
                    if diff:LengthSqr() <= r2 then
                        result[#result + 1] = p
                    end
                end
            end
        end
    end
    return result
end

-- Usage (server think or concommand):
-- local nearby = PlayersNear(attacker:GetPos(), 512, player.GetAll())
```

Reason: Spatial hashing skips `ents.FindInSphere` entirely — O(players) insert + O(cells in radius) lookup instead of O(all entities) scan, with length-squared checks replacing sqrt for the final distance gate.


```lua
local sum = 0
for i = 1, n do
  sum = sum + i
end
```

Reason: The numeric `for` loop is faster because its increment and bounds check are implemented in C inside the Lua VM, while a `while` loop requires explicit Lua-level assignment and comparison each iteration.


```lua
-- FASTER: hook.Run once, iterate players inside
hook.Run("GModBenchTick", player.GetAll())

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

Reason: A single hook call avoids repeated hook-name lookups, argument packing, and per-call overhead that scales with player count; one iteration inside the hook is cheaper than N separate hook invocations.


```lua
hook.Add("HUDPaint", "OptimizedHealthHUD", function()
    local hp = LocalPlayer():Health()
    -- draw call 1 using hp
    surface.SetTextColor(255, 0, 0)
    surface.SetTextPos(50, 50)
    surface.DrawText("Health: " .. hp)
    -- draw call 2 using hp
    draw.RoundedBox(4, 50, 80, hp, 20, Color(255, 0, 0))
    -- draw call 3 using hp
    surface.DrawText("Health: " .. hp)
end)
```

Reason: Caching `LocalPlayer():Health()` into a local avoids two redundant method calls, table lookups, and the C→Lua bridge crossing per frame.


```lua
local colWhite = Color(255, 255, 255)
function PANEL:Paint(w, h)
    surface.SetDrawColor(colWhite)
    surface.DrawRect(0, 0, w, h)
end
```

Reason: Hoisting the Color allocation out of the paint callback into an upvalue eliminates per-frame table creation and GC pressure.


```lua
local sin = math.sin
for i = 1, n do
  result[i] = sin(x[i])
end
```

Reason: Caching `math.sin` as a local eliminates the two-step table lookup (`math` then `sin`) on every iteration, and locals resolve faster than globals in Lua's register-based VM.


```lua
local ply = LocalPlayer()

function DoSomething()
    if not IsValid(ply) then return end
    ply:ChatPrint("hello")
end

hook.Add("Think", "Example", function()
    if not IsValid(ply) then return end
    ply:SetNWInt("foo", 1)
end)
```

Reason: LocalPlayer() walks a chain each call; caching it in a local at file scope and guarding with IsValid() eliminates the repeated lookup while staying safe across disconnects.


```lua
-- Returns true when each player's aim direction points toward the other (dot > threshold).
-- Uses AimVec (forward) from each player; cheaper than angle calculations.
local function PlayersFacingEachOther(ply1, ply2)
    local pos1, pos2 = ply1:GetPos(), ply2:GetPos()
    local dir1 = ply1:GetAimVector()          -- unit forward of ply1
    local dir2 = ply2:GetAimVector()          -- unit forward of ply2
    local toOther = pos2 - pos1               -- vector from 1 to 2

    -- Both must be pointing roughly toward the other:
    --   dir1 . (pos2-pos1) > 0  means ply1 aims toward ply2
    --   dir2 . (pos1-pos2) > 0  means ply2 aims toward ply1
    -- Threshold 0.5 ≈ ±60° cone (cos(60°) = 0.5)
    return toOther:Dot(dir1) > 0 and toOther:Dot(dir2) < 0
end
```

Reason: Two dot products with pre-computed directions replace `math.acos` and angle subtraction, staying in vector-ops only and well under a microsecond per pair.


```lua
-- Preferred: local function, direct call
local function SomeHelper(ply)
  -- implementation
end

-- At the call site, prefer:
SomeHelper(ply)       -- local lookup + direct call
-- over:
ply:SomeHelper()      -- metatable chain traversal + method lookup on every call
```

Reason: `ply:SomeHelper()` is sugar for `ply.SomeHelper(ply)`, which forces a table/metatable lookup on the entity each call; a local function call resolves at load time and skips that chain.


```lua
MsgN( "debug_value = ", tostring( myVar ) )
```

Reason: MsgN avoids the string.format overhead that print uses internally and writes directly to the console.


```lua
local t = {} -- large sequential table of numbers
local sum = 0
for i = 1, #t do
    sum = sum + t[i]
end
```

Reason: `for i = 1, #t` avoids per-iteration function-call overhead (pairs/ipairs call an iterator function each iteration) and avoids hash-table lookups (pairs is unordered); the numeric for compiles to a tight C loop in LuaJIT, and `#t` is cached by the compiler, making it the fastest idiom for dense sequential arrays.


```lua
-- DarkRP fn library wraps each call in closures and currying.
-- A plain loop with early-out avoids the overhead entirely.

local function filterMap(list, predicate, transform)
    local out = {}
    local n = 0
    for i = 1, #list do
        local v = list[i]
        if predicate(v) then
            n = n + 1
            out[n] = transform(v)
        end
    end
    return out
end

-- Example: get names of alive players longer than 3 chars.
local result = filterMap(
    player.GetAll(),
    function(p) return p:Alive() end,
    function(p) return p:Nick() end
)
```

Reason: DarkRP's `fn` library allocates a closure per combinator call and walks tables via `ipairs` metamethod indirection; a single fused loop with numeric indexing eliminates both the per-element allocations and the iterator overhead, yielding measurable speedups on large tables (e.g. 100+ entity lists) where GC pressure and call depth compound.


```lua
-- Cached player list — refreshed only on PlayerInitialSpawn / PlayerDisconnect
local CachedPlayers = {}
local PlayersDirty = true

local function RebuildPlayerCache()
    CachedPlayers = player.GetAll()
    PlayersDirty = false
end

hook.Add("PlayerInitialSpawn", "PlayerCache_Init", function(_ply)
    PlayersDirty = true
end)

hook.Add("PlayerDisconnect", "PlayerCache_Disc", function(_ply)
    PlayersDirty = true
end)

-- Any per-tick hook that needs the player list
hook.Add("Think", "PlayerCache_Think", function()
    if PlayersDirty then
        RebuildPlayerCache()
    end

    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        -- your per-player logic here
    end
end)
```

Reason: `player.GetAll()` allocates a new table every call; caching it and refreshing only on join/leave avoids that per-tick GC pressure while `PlayersDirty` guarantees the list stays current.


```lua
-- Per-player temp store keyed by entity index (pure Lua table, integer keys)
local PlyTemp = {}

-- Write (once):
PlyTemp[ply:EntIndex()] = value

-- Read (hot path):
local v = PlyTemp[ply:EntIndex()]
```

Reason: `ply.someField` crosses into C through the entity userdata's `__index`/`__newindex` metamethods on every access; an external Lua table keyed by `EntIndex()` is a pure-Lua integer-keyed lookup that LuaJIT compiles to a direct array slot read with zero C-boundary overhead.


Answer must contain 0 through 1 candidate loops.

```lua
-- Sequential array: faster iteration
local arr = {10, 20, 30, 40, 50}
for i = 1, #arr do
    local v = arr[i]
end

-- String-keyed map: slower iteration
local map = {a = 10, b = 20, c = 30, d = 40, e = 50}
for k, v in pairs(map) do
    -- k is hashed, iteration order non-deterministic
end
```

Reason: Sequential integer-indexed arrays allow Lua's VM to use contiguous memory traversal with simple pointer arithmetic, while string-keyed maps require hash computation for each access and use non-deterministic iteration order with higher overhead per element.


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

Reason: The variadic r,g,b,a style avoids allocating a `Color` table each frame, eliminating GC pressure and table-creation overhead in a hot path.


```lua
sql.Query("CREATE TABLE IF NOT EXISTS players (steamid TEXT PRIMARY KEY, data TEXT)")
sql.QueryValue("SELECT data FROM players WHERE steamid = " .. sql.SQLStr(steamid))
sql.Query("INSERT OR REPLACE INTO players (steamid, data) VALUES (" .. sql.SQLStr(steamid) .. ", " .. sql.SQLStr(data) .. ")")
```

Reason: Local SQLite eliminates network round-trips entirely, making reads/writes near-instantaneous compared to remote MySQL's inherent latency overhead.


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

local function CachedSteamID(ply)
  local sid = idCache[ply]
  if sid then return sid end
  sid = ply:SteamID()
  idCache[ply] = sid
  return sid
end
```

Reason: Weak-keyed table caches per-entity without preventing GC; avoids repeated string allocation and API overhead on hot paths.


Answer must contain 0 through 0 candidate loops.

```lua
-- Slow: repeated .. concatenation
local function buildSlow(n)
    local s = ""
    for i = 1, n do
        s = s .. "x"
    end
    return s
end

-- Fast: table.concat
local function buildFast(n)
    local t = {}
    for i = 1, n do
        t[i] = "x"
    end
    return table.concat(t)
end
```

Reason: `..` copies the entire accumulator string on every append (O(n²) total copies), while `table.concat` builds a table of pieces in O(1) amortized appends then joins them in a single O(n) pass.


```lua
surface.DrawTexturedRect(x, y, w, h)
```

Reason: `draw.RoundedBox(0, ...)` still validates corner-radius, clamps arguments, and pushes extra lua-side overhead before calling `surface.DrawTexturedRect` internally; calling `surface.DrawTexturedRect` directly skips that wrapper, but you must bind a 1×1 white material with `surface.SetMaterial`/`surface.SetDrawColor` first.


```lua
-- set font ONCE (Init or first frame guard), not every Draw call
local fnt = "DermaLarge"
surface.SetFont(fnt)

-- in your HUDPaint / Paint hook
local txt = "Hello"
local tw, th = surface.GetTextSize(txt)
local x, y = ScrW() / 2 - tw / 2, ScrH() / 2 - th / 2
surface.SetTextPos(x, y)
surface.DrawText(txt)
```

Reason: `draw.DrawText` and `draw.SimpleTextOutlined` rebuild the font object and reset draw state on every call; a single `surface.SetFont` outside the hook plus raw `surface.DrawText`/`SetTextPos` avoids that per-frame overhead.


```lua
local t = {1, 2, 3, 4, 5}
local len = #t
print(len) -- 5
```

Reason: The unary `#` operator is the idiomatic and canonical way to get the length of a sequence table in Lua; `table.getn` is deprecated.


```lua
-- Faster: t = {} simply reassigns; table.Empty iterates every index to nil it
local t = {}
-- fill t with 1,000,000 entries...
t = {} -- GC reclaims the old table when ready; no per-key loop
```

Reason: `t = {}` is a single pointer reassignment and lets the GC reclaim the old table in bulk, while `table.Empty` must iterate every occupied index to set it to `nil`, making it O(n) in the hot path.


```lua
-- Build a lookup set once
local mySet = {
  ["alpha"] = true,
  ["bravo"] = true,
  ["charlie"] = true,
}

-- O(1) membership test vs table.HasValue O(n) scan
if mySet[value] then
  -- value exists
end
```

Reason: Table-key lookup is O(1) hash access, while table.HasValue does a linear O(n) array scan.


```lua
-- Faster: fields in the constructor
local t = { name = "foo", hp = 100, active = true }

-- Slower: assign after construction
local t = {}
t.name = "foo"
t.hp = 100
t.active = true
```

Reason: The constructor populates fields in a single C-level pass with one hash-part allocation, while separate assignments each trigger an individual hash insertion and resize check, adding overhead.


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

Reason: `math.random(#t)` is O(1) vs `table.Random`'s O(n) copy-and-shuffle, and sequential tables have no gaps so direct indexing is always safe.


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

Reason: Multiplication is faster than `math.pow` (which handles fractional exponents and has overhead) or `x^2` (which invokes the generic power operator with exponent parsing).


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

```lua
for _, ply in player.Iterator() do
    -- your code here
end
```
Reason: Using `player.Iterator()` is the modern, memory-efficient way to loop over connected players in Garry's Mod Lua.


```lua
for ent in ents.Iterator("prop_physics") do
  -- do something with ent
end
```
Reason: `ents.Iterator()` yields entities one at a time rather than building a table of all matches, so it visits only `prop_physics` entities and avoids allocating an intermediate table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` registers a callback for a named hook; the first argument is the hook name (`"Think"`), the second is a unique identifier for removal or override, and the third is the function to run each frame.


```lua
if not IsValid(ent) then return end
```
Reason: `IsValid` returns false for nil entities and for entities that have been removed from the world (via `Entity:Remove()`), preventing crashes from calling methods on freed C++ objects.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: `net.Receive` is the standard GMod net library function that registers a callback for an incoming net message identified by the given name string.


```lua
local ZERO = Angle(0, 0, 0)
-- Hot path: reuse instead of allocate
ang:Set(ZERO)
```
Reason: `Angle(0, 0, 0)` allocates a new C-side userdata every call (heap alloc + GC pressure), while `:Set()` or `:Zero()` writes three floats in-place with zero allocation.


```lua
local COLOR = Color(255, 0, 0)
local col = COLOR
--
```

Reason: A local variable resolves in a single VM instruction (LOADREG), while nested table lookups (`myaddon.config.color`) require one hash-table probe per dot after the initial global lookup — three probes vs one, which adds up in hot paths like hooks or render loops.


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

Reason: `ply:getDarkRPVar("job")` is the official, documented DarkRP API — it reads from the same networked variable but is future-proof against internal renames, more readable, and automatically handled by DarkRP's own variable system instead of relying on a raw engine call that could break with addon updates.


```lua
if a:DistToSqr(b) < threshold^2 then
```

Reason: `DistToSqr` avoids the expensive `math.sqrt` call that `Distance` performs internally, making threshold checks significantly faster when the actual distance value is not needed.


```lua
for ent in ents.Iterator() do
    -- visit every entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator as it avoids allocating a table of all entities (unlike `ents.GetAll()`), using a lightweight cursor instead for better performance in loops that visit every entity.


```lua
local ents = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: `FindInSphere` uses the engine's spatial hash grid for near-O(1) lookup within a radius, beating `FindInBox` (AABB cheaper but over-fetches) and `FindInCone` (adds angle filtering cost) in head-to-head entity benchmarks when you only need simple proximity.


```lua
local function FindPlayersInRadius(pos, radius)
    local players, radiusSq = {}, radius * radius
    for i = 1, #player.GetAll() do
        local ply = player.GetAll()[i]
        if ply:IsValid() and ply:Alive() then
            local diff = ply:GetPos() - pos
            if diff:Dot(diff) <= radiusSq then
                players[#players + 1] = ply
            end
        end
    end
    return players
end
```
Reason: `ents.FindInSphere` scans the entire world's spatial index (props, ragdolls, NPCs — potentially thousands of ents) then filters, while `player.GetAll()` iterates only the N online players with a squared-distance `Dot` check that skips `math.sqrt`.


```lua
for i = 1, n do end
```
Reason: The `for` loop compiles to dedicated FORPREP/FORLOOP bytecodes with internal iteration and bounds caching, while `while` emits separate comparison, increment, and jump instructions — LuaJIT's trace compiler also optimizes the `for` loop form more aggressively via SSA and loop unrolling.


```lua
-- Faster: single hook.Run with all players
hook.Run("TickAllPlayers", player.GetAll())
```
Reason: `hook.Run` has non-trivial overhead per call (global table lookup, hook table iteration, function dispatch); calling it once amortizes that cost across all players instead of multiplying it by player count.


```lua
local health = LocalPlayer():Health()
-- use health three times instead of calling :Health() each time
```
Reason: Caches the return value in a local variable, avoiding three table lookups and three function calls per frame.


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

Reason: `Color()` allocates a new table every call; caching it in a local variable outside the loop avoids per-frame allocation and GC pressure.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```
Reason: Local variable access is faster than hash table lookup in Lua/LuaJIT; caching `math.sin` in a local avoids the table indexing overhead on every iteration.


```lua
local ply = LocalPlayer()
-- use ply instead of calling LocalPlayer() repeatedly
```
Reason: `LocalPlayer()` is a C function call that traverses the entity list each invocation; caching it in a local variable avoids that lookup on every frame.


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

Reason: Dot products are scalar multiplies and adds — no trig, no acos, no branches beyond the two compares. `aimA:Dot(dir) > 0.5` means A's aim is within ~60° of B's position (equivalent to `angle < 60°`). Reusing `dir` and its negation avoids a second subtraction-and-normalize.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` avoids the metatable lookup that `ply:SomeHelper()` requires, since the method syntax desugars to `ply.SomeHelper(ply)`, which walks the metatable chain. A directly-referenced local function eliminates that overhead.


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

Reason: `print` calls `tostring` on each argument, joins them with tabs, and routes through GMod's verbose print handler with allocation and formatting overhead; `MsgN` writes directly to the engine's raw console output path with no intermediate formatting.


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

Reason: Numeric for avoids per-iteration function call overhead from iterator generation (`pairs`/`ipairs`) and length recomputation, compiling to a single `OP_LOADK` + `OP_GETTABLE` + `OP_FORPREP`/`OP_FORLOOP` bytecode sequence with no closure or coroutine overhead.


```lua
-- DarkRP fn approach (slower): creates many closures
local filtered = fn.Compose(
  fn.Filter(function(item) return item.quality > 5 end),
  fn.Map(function(item) return item.name end)
)(items)

-- Plain Lua approach (~2-4x faster): one loop, no closure overhead, preallocated
local function fast_pipeline(items)
  local out, n = {}, 0
  for i = 1, #items do
    local item = items[i]
    if item.quality > 5 then
      n = n + 1; out[n] = item.name
    end
  end
  return out
end
```
Reason: `fn.Compose`/`fn.Filter`/`fn.Map` create intermediate closures and allocate intermediate tables per pipeline stage; a single for-loop avoids all function-call overhead and table churn, keeping the hot path inline for LuaJIT's JIT compiler.


```lua
local cachedPlayers = {}

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

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

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

Reason: `player.GetAll()` allocates a new table every call; caching it avoids per-tick allocation and garbage collection, replacing O(n) table creation each tick with O(1) table reads from a pre-built cache that only refreshes on join/leave events.


```lua
-- Pre-allocate array by EntIndex for O(1) reads, bypassing metatable overhead
local PD = {}
for i = 1, game.MaxPlayers() do PD[i] = {} end
hook.Add("PlayerDisconnected", "PDClean", function(ply) PD[ply:EntIndex()] = {} end)

-- Read:   PD[ply:EntIndex()].foo
-- Write:  PD[ply:EntIndex()].foo = val
```
Reason: `ply.EntIndex` returns a small integer, so `PD[entIndex]` hits the array part of the table (single C-side `array[i]` load), while `ply.field` traverses the full Lua metatable chain on a userdata — the second lookup, the metatable, and the `__index` metamethod are all skipped entirely.


```lua
-- Fast: sequential number-indexed array
local t = {"a", "b", "c", "d"}
for i, v in ipairs(t) do end

-- Slow: string-keyed map
local t = {a = 1, b = 2, c = 3, d = 4}
for k, v in pairs(t) do end
```

Reason: Sequential arrays in LuaJIT are stored as a contiguous C array (the "array part"), enabling cache-friendly sequential memory access and heavy JIT compiler optimizations, while string-keyed maps require hashing each key and traversing a sparse hash table with pointer chasing.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numbers avoids allocating a Color table and its metatable, eliminating GC pressure in a hot loop.


```lua
sql.Query("SELECT steamid, kills, deaths FROM player_stats WHERE steamid = '" .. sql.SQLStr(ply:SteamID()) .. "'")
```

Reason: Local SQLite uses direct file I/O without network overhead, while remote MySQL adds TCP round-trip latency for every query regardless of query complexity.


```lua
-- cache once, reuse forever
local steamid_cache = setmetatable({}, {__mode = "k"})

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

Reason: `ply:SteamID()` formats and allocates a new string every call; weak-table keyed on the player object avoids both repeated formatting and leaking dead player entries.


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

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

Reason: Lua strings are immutable; `..` allocates a new string on every operation, yielding O(n²) time and excessive GC pressure, while `table.concat` precomputes the final size, allocates once, and fills in O(n).


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

Reason: `draw.RoundedBox` internally processes a rounding path even at radius 0 (material setup, segment calculation), while `surface.DrawRect` is a direct pixel-fill primitive with no branching or geometry manipulation.


```lua
surface.SetFont("MyFont")
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetTextPos` + `surface.DrawText` bypass the alignment math, color wrapping, and per-frame allocation that `draw.DrawText` and `draw.SimpleTextOutlined` incur internally, making it the fastest path for raw single-line rendering.


```lua
#t
```

Reason: The `#` operator (length operator) is the idiomatic and fastest way to get the length of a sequential array-like table in Lua/Garry's Mod Lua, directly implemented in the VM with O(log n) worst-case or O(1) for arrays without holes.


```lua
t = {}
```
Reason: `table.Empty(t)` is O(n) — it iterates every element to remove it — while `t = {}` is O(1): it simply reassigns the variable to a new empty table, leaving the old table for garbage collection.


```lua
local set = { apple = true, banana = true, cherry = true }
if set[value] then end
```
Reason: table.HasValue iterates the entire list linearly (O(n)), whereas a set table uses direct key lookup (O(1)), which is hash-table based and does not scan.


```lua
-- Faster
local t = {a = 1, b = 2}

-- Slower
local t = {}
t.a = 1
t.b = 2
```
Reason: In GMod Lua, table constructor assignments bypass `__newindex` and the internal panel/entity tracking hooks that fire on every separate field write, making the literal form measurably faster for small tables with known keys.


```lua
local val = tbl[math.random(#tbl)]
```
Reason: Avoids the function call overhead and internal branches of table.Random, reducing to a single math.random call plus array index.


```lua
x * x
```
Reason: `x * x` avoids the function call overhead of `x ^ 2` (which calls `math.pow` internally) and compiles to a single arithmetic bytecode instruction, making it the fastest option in a tight loop.


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

Reason: `player.Iterator()` returns a direct iterator over the internal player array, avoiding the temporary table allocation and key-value pair overhead of `pairs(player.GetAll())`.


```lua
for ent in ents.Iterator() do
  if ent:GetClass() == "prop_physics" then
    -- visit ent
  end
end
```
Reason: `ents.Iterator()` returns a C-side generator that yields entities one at a time without ever allocating a Lua table of all entities, unlike `ents.GetAll()` or `ents.FindByClass()`.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` registers a function to run on every frame for the `Think` event, using `"MyAddon.Think"` as the unique identifier so it can be later removed with `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 hasn't been removed from the world, preventing errors from calling methods on freed entity objects.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: `net.Receive` registers a callback for a named net message; the first argument is the message name as a string, the second is the function invoked when the client receives that message.


```lua
local zero = Angle()
-- In hot path, instead of local a = Angle():
zero:Set(0, 0, 0)
```
Reason: Constructing `Angle()` allocates a new C userdata every call, pressuring the GC. Reusing a pre-allocated Angle via `:Set(0,0,0)` mutates the existing object with zero allocations.


```lua
local color = Color(255, 0, 0) -- declared once
-- read: just use color
```

Reason: Local variable access is a single register index (Lua's fastest operation), while nested tables require a hash lookup for each level of indexing.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP's `ply:getDarkRPVar("job")` is the official, stable API that abstracts the internal netvar implementation, while `ply:GetNWString("job")` ties your code to an internal network string name that could change between versions or be overridden by other addons.


```lua
local threshold = 100
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the expensive `sqrt` call that `DistTo` computes, since comparing squared distances against a pre-squared threshold is mathematically equivalent and significantly faster.


```lua
for _, ent in ents.Iterator() do
    -- visit entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator because it avoids allocating a table (unlike `ents.GetAll()`), yielding the entity pointer directly from the engine's internal linked list for each iteration step.


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

Reason: `FindInSphere` uses the engine's BSP-based spatial partitioning to query a sphere of interest directly, requiring no precomputed set or PVS traversal, and is consistently the fastest general-purpose `FindIn*` variant for point-centric proximity queries in server benchmarks.


```lua
local function FindPlayersInRadius(pos, radius)
    local r2 = radius * radius
    local out = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:IsValid() and ply:GetPos():DistToSqr(pos) <= r2 then
            out[#out + 1] = ply
        end
    end
    return out
end
```
Reason: `ents.FindInSphere` must traverse the spatial partition (hundreds to thousands of ents), allocating a table of non-player ents that are immediately discarded, while `player.GetAll()` returns only the player set (typically 1–128) and `DistToSqr` avoids the `sqrt` call in `GetPos():Distance`, making it O(#players) instead of O(#all-ents) with less allocation and no spatial lookup.


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

Reason: LuaJIT compiles `for` into specialized bytecodes (`FORPREP`/`FORLOOP`) that are monomorphic and fully JIT-compilable, while `while` with a manual counter produces more bytecode and is harder for the trace compiler to optimize.


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

Reason: `hook.Run` internally iterates all registered hooks, so a per-player loop multiplies that lookup/iteration overhead by player count; batching reduces it to one dispatch pass regardless of server population.


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

-- Draw call 1 using health
draw.SimpleText(health, "Default", 10, 10, COLOR_WHITE)
-- Draw call 2 using health
draw.SimpleText(health, "Default", 10, 30, COLOR_WHITE)
-- Draw call 3 using health
draw.SimpleText(health, "Default", 10, 50, COLOR_WHITE)
```

Reason: `LocalPlayer():Health()` is a networked C++ call with VM marshalling overhead — caching the result in a local variable avoids three crossings of the Lua/C boundary per frame for a value that doesn't change within a single frame.


```lua
local white = Color(255, 255, 255)
hook.Add("PostDrawOpaqueRenderables", "example", function()
    surface.SetDrawColor(white)
end)
```
Reason: `Color()` allocates a new table each call; caching it as a local avoids per-frame GC pressure from allocating ~60 Color objects per second.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```
Reason: Localizing the function avoids a global table lookup and the `self`-dispatch overhead of colon-call syntax on every iteration.


```lua
local ply = LocalPlayer()
```
Reason: Assigning LocalPlayer() to a local variable outside of hooks avoids the overhead of the internal C-side lookup on every frame/hook call, since Lua locals are faster than repeated engine function calls.


```lua
local function LookingAtEachOther(a, b, threshold)
    threshold = threshold or 0.7
    local dir = (b:GetPos() - a:GetPos()):GetNormalized()
    return a:GetAimVector():Dot(dir) > threshold and b:GetAimVector():Dot(dir) < -threshold
end
```
Reason: A single normalized direction vector is computed once; both checks reduce to dot-product comparisons against a threshold, avoiding the implicit math.acos in angle-from-vectors entirely.


```lua
ply:SomeHelper()
```
Reason: In GMod Lua (Lua 5.1), `ply:SomeHelper()` is generally faster than the global `SomeHelper(ply)` because method lookup goes through the smaller player metatable rather than the much larger global table `_G`, and the `:` syntax adds zero overhead — it's just sugar for `ply.SomeHelper(ply)`.


```lua
MsgN("debug text")
```
Reason: `print()` triggers the `ConsoleMessage` hook and does string formatting overhead; `MsgN` writes directly to the console via the engine, skipping hook dispatch entirely.


```lua
for i = 1, #t do local v = t[i] end
```
Reason: Numeric for compiles to minimal bytecode (no iterator call overhead like pairs/ipairs) and LuaJIT can fully JIT-compile the tight loop with direct array indexing, making it 2-5x faster than ipairs and far faster than pairs on sequential arrays.


```lua
-- fn (slow, creates closures + intermediate tables for each stage)
-- local names = fn.Compose(fn.Map(fn.Curry(fn.Select, 2)(1)), fn.Filter(function(v) return v > 10 end))(values)

-- plain Lua (fast: single pass, no closures, no allocations beyond the result table)
local n, result = 0, {}
for i = 1, #values do
    local v = values[i]
    if v > 10 then
        n = n + 1
        result[n] = v
    end
end
```
Reason: DarkRP's `fn` combinators allocate a closure per combinator, traverse the list once per stage (no fusion), and use JIT-unfriendly vararg packing (`select`, `{...}`); a plain for-loop fuses filter+map into a single pass with zero closures and one allocation, letting LuaJIT compile tight, branch-predictable bytecode.


```lua
local cachedPlayers = {}

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

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

hook.Add("Tick", "MyTickHook", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
    end
end)

RefreshPlayerCache()
```
Reason: `ipairs(player.GetAll())` allocates a new iterator closure and table reference every tick; caching replaces that with a numeric `for` over a pre-built table, refreshed only on the two player-lifecycle events instead of 66 times per second.


```lua
local pts = setmetatable({}, { __mode = "k" })
-- write: pts[ply] = { hp = 100 }
-- read:  pts[ply].hp
```
Reason: Entity metatables add overhead on every field access (`ply.foo` traverses `__index`); a plain Lua table with weak keys avoids that chain entirely, making reads a single hash lookup instead of a C metamethod walk.


```lua
-- Fast: sequential integer-indexed array
for i = 1, #arr do
  local v = arr[i]
end

-- Slow: string-keyed map
for k, v in pairs(map) do
end
```
Reason: LuaJIT allocates sequential integer keys in the array part (contiguous memory, cache-friendly, O(1) direct index), while string keys live in the hash part (pointer chasing, hash computation, worse cache behavior).


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing raw numbers avoids allocating a Color object on every call, eliminating per-frame GC pressure in a hot draw path.


```lua
sql.Query("SELECT data FROM player_data WHERE steamid = " .. SQLStr(ply:SteamID64()))
```

Reason: SQLite reads and writes directly to a local file with zero network overhead, while MySQL requires a TCP round-trip to a remote server, adding 1–10ms+ of latency per query depending on network conditions.


```lua
local steamid_cache = setmetatable({}, {__mode = "k"})
function cached_steamid(ply)
    local id = steamid_cache[ply]
    if id then return id end
    id = ply:SteamID()
    steamid_cache[ply] = id
    return id
end
```
Reason: `ply:SteamID()` calls into C++, which serializes the 64-bit ID to a string each invocation. A weak-keyed cache stores the result once per player object and lets dead players be GC'd automatically, eliminating all repeated C++ string allocations and format work.


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

-- Fast: table.concat
local parts = {}
for i = 1, 10000 do
    parts[i] = tostring(i) .. ","
end
local s = table.concat(parts)
```
Reason: Each `..` concatenation allocates a new string and copies both operands, O(n²) total; `table.concat` precomputes the total length, allocates once, and copies each piece exactly once, O(n).


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox` adds Lua function-call overhead and an unnecessary zero-radius branch check before dispatching to the same surface primitive, so calling `surface.SetDrawColor` + `surface.DrawRect` directly eliminates that overhead.


```lua
surface.SetFont("MyFont")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText("Hello")
```
Reason: `surface.SetTextPos` + `surface.DrawText` avoids the allocation, branching, and extra function-call overhead of `draw.DrawText` (which wraps surface calls with validation) and `draw.SimpleTextOutlined` (which draws twice for outline + fill).


```lua
#t
```
Reason: In Garry's Mod Lua (Lua 5.1), the `#` operator is the idiomatic and efficient way to get the length of a sequential array-like table, returning the last numeric key with a non-nil value.


```lua
-- Faster approach: t = {}
t = {}
```

Reason: `t = {}` is O(1) — it simply creates a new empty table and reassigns the variable, while `table.Empty(t)` is O(n) because it must iterate through and remove every element in the table before the GC collects the now-empty container.


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

Reason: `table.HasValue` iterates the entire list O(n) per check, while a hash-map lookup (`table[key]`) is O(1) because Lua tables are associative arrays with direct key addressing.


```lua
local t = {a = 1, b = 2, c = 3}
```
Reason: The table constructor pre-allocates the hash part to fit the given fields in a single allocation, avoiding the rehashing that each `t.key = val` assignment may trigger on an initially empty table.


```lua
local element = t[math.random(#t)]
```
Reason: `table.Random` has overhead for non-sequential tables; `math.random(#t)` indexes directly into the contiguous array part with O(1) operations and no function dispatch.


```lua
local s = x * x
```
Reason: `x * x` compiles to a single bytecode instruction (`MUL`), while `x ^ 2` calls the C math library's exponentiation function, which handles general cases with log/exp and has function call overhead.


```lua
for _, ply in player.Iterator() do
    -- do something with ply
end
```
Reason: `player.Iterator()` returns a direct closure iterator that avoids allocating a table on every call, unlike `player.GetAll()` which creates a new table each frame.


```lua
for _, ent in ents.Iterator("prop_physics") do
  -- ent is a prop_physics entity
end
```
Reason: `ents.Iterator` uses an internal C iterator that visits matching entities one at a time without allocating a full table of all entities.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` registers a named callback on the Think hook; the name prevents duplicate registration and allows targeted removal.


```lua
if IsValid(ent) then
  -- safe to use ent here
end
```

Reason: `IsValid` checks for nil, verifies the entity hasn't been removed by the engine, and ensures the internal CBaseEntity pointer is still alive; calling methods on an invalid entity throws a Lua error.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: net.Receive registers a callback for an incoming net message by name.


```lua
local zero = Angle()
-- In hot path, reuse and zero in-place instead of allocating a new Angle():
zero.p, zero.y, zero.r = 0, 0, 0
```

Reason: Allocating a new `Angle()` in a hot path adds GC pressure and memory allocation overhead; reusing one table and resetting its fields in-place avoids both, giving a measurable speedup.


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

-- Read
surface.SetTextColor(color)
```

Reason: A local variable is a single register/upvalue index into the function's stack frame, while nested table access (`myaddon.config.color`) requires three sequential string-hash lookups — one per table — each with hashing, bucket probing, and collision checks.


```lua
ply:getJobTable().name
```
Reason: DarkRP sets and manages the NWString internally; reading it directly bypasses DarkRP's internal state and may break if DarkRP ever changes its networking internals. `ply:getJobTable()` returns the authoritative job definition table where `.name` lives alongside other job data (salary, weapons, etc.), and it's the documented, stable API that respects DarkRP's own lifecycle.


```lua
if vec1:DistToSqr(vec2) < thresholdSqr then
```

Reason: `DistToSqr` returns the squared distance, avoiding the expensive `sqrt()` call that `Distance` requires—since comparing squared distances against a pre-squared threshold yields the same boolean result with fewer CPU cycles.


```lua
for ent in ents.Iterator() do
    -- visit ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator that yields entities one at a time without allocating a table, unlike `pairs(ents.GetAll())` which creates a full table of all entities before iterating.


```lua
ents.FindInSphere(ply:GetPos(), 128)
```

Reason: FindInSphere with a small radius (128-256) is the fastest general-purpose spatial query in GMod benchmarks — it uses a single OBB-sphere overlap test per entity with no angular math, no transient table allocation beyond the result list, and avoids PVS bitfield scanning entirely.


```lua
local function PlayersInRadius(pos, radius)
    local sqrRadius = radius * radius
    local players = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= sqrRadius then
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: `ents.FindInSphere` enumerates all entity types via spatial hashing (thousands of checks), then you filter by class; iterating `player.GetAll()` directly does at most N distance-squared checks where N = player count (usually 32–128), avoiding the spatial scan entirely.


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

Reason: Lua's numeric `for` compiles to specialized VM instructions (FORPREP/FORLOOP) that avoid a separate counter variable, bounds check on every iteration, and function call overhead, whereas `while` compiles to a conditional jump + manual increment and comparison, which is always at least as many bytecode ops.


```lua
local players = player.GetAll()
hook.Run("TickPlayerLogic", players)
```
Reason: Each `hook.Run` call incurs string lookup, hook table iteration, and function dispatch overhead; looping per player multiplies that cost by player count, so batching all players into one call is faster.


```lua
local ply = LocalPlayer()
local health = ply:Health()
draw.SimpleText(health, "Default", 10, 10, color_white)
draw.SimpleText(health, "Default", 10, 30, color_white)
draw.SimpleText(health, "Default", 10, 50, color_white)
```

Reason: `LocalPlayer()` and `:Health()` are called once and cached locally, avoiding two redundant network-value lookups and three JIT boundary crossings in a single frame.


```lua
local WHITE = Color(255, 255, 255)
hook.Add("PostDrawOpaqueRenderables", "draw", function()
    render.SetColorMaterial()
    render.DrawQuadEasy(Vector(0,0,0), Vector(0,0,1), 512, 512, WHITE)
end)
```

Reason: `Color()` allocates a new table on every call; hoisting it to a `local` outside the loop avoids per-frame GC pressure and table lookup overhead.


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

Reason: Caching `math.sin` in a local variable avoids a global table lookup (`math`) followed by a member table lookup (`sin`) on every iteration, instead resolving to a single upvalue access.


```lua
local ply = LocalPlayer()
-- Use `ply` instead of calling LocalPlayer() repeatedly
```
Reason: `LocalPlayer()` is a C callback that walks the entity list each call; caching it in a local variable on the upvalue saves a table lookup and C boundary crossing on every reference.


```lua
local function LookingAtEachOther(a, b, cosThreshold)
    cosThreshold = cosThreshold or 0.7071
    local dirAtoB = (b:GetPos() - a:GetPos()):GetNormalized()
    return a:GetAimVector():Dot(dirAtoB) > cosThreshold
        and b:GetAimVector():Dot(-dirAtoB) > cosThreshold
end
```
Reason: Dot product of unit vectors *is* cos(angle); comparing it directly against a threshold replaces the inverse trig call with one multiply-add per player, same precision, no branch mispredict from acos's domain check.


```lua
SomeHelper(ply)
```
Reason: Direct function call skips the metatable lookup, making it strictly faster than colon syntax which must resolve the method through the player's metatable chain.


```lua
if DEBUG then MsgN("debug line") end
```
Reason: `print` is a C vararg function with string formatting overhead; `MsgN` is a direct raw-output call. Guarding with a constant (`DEBUG = false`) lets LuaJIT dead-code-eliminate the entire call in the hot path when debug is off.


```lua
for i = 1, #t do
  local v = t[i]
end
```
Reason: Numeric for avoids per-iteration function call overhead (no iterator closure like ipairs/pairs), compiles to raw bytecode instructions, and the length operator is evaluated once before the loop body begins.


```lua
-- Faster: plain for-loop pipeline instead of fn combinators
local function transform(entities)
    local out = {}
    for i = 1, #entities do
        local e = entities[i]
        if e:IsValid() and e:GetPos().z > 0 then
            out[#out + 1] = e:GetClass()
        end
    end
    return out
end

-- Equivalent with fn:
-- fn.Compose(fn.Map(fn.Curry(fn.Prop)(1, "GetClass")), fn.Filter(fn.Curry(function(e) return e:IsValid() and e:GetPos().z > 0 end)))(entities)
```

Reason: `fn` combinators create a new closure per composition step (Curry, Compose, Map, Filter all allocate), then invoke each through multiple call frames per element; a single plain for-loop eliminates all intermediate closures and does one allocation (the result table) with one loop, no per-element function call overhead.


```lua
local playerCache = {}

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

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

hook.Add("Tick", "CachedPlayerLoop", function()
    for i = 1, #playerCache do
        local ply = playerCache[i]
        -- use ply
    end
end)
```
Reason: `player.GetAll()` allocates a new table each call; calling it every tick creates unnecessary GC pressure and wastes CPU. Caching it and invalidating only on join/leave (PlayerInitialSpawn/PlayerDisconnected) eliminates the per-tick allocation while staying correct, since the player list only changes at those events.


```lua
local data = {}
local mt = {__mode = "k"}; setmetatable(data, mt)

hook.Add("PlayerDisconnected", "CleanupPlayerData", function(ply)
  data[ply] = nil
end)

-- store: data[ply] = {field = value}
-- read:  data[ply].field
```
Reason: Direct table indexing (`data[ply]`) is faster than dot-access on a player Entity (`ply.field`) because Entity metatables add overhead on every field access, while Lua table rawget is a single hash lookup — and the weak-keyed metatable (`__mode = "k"`) lets GC clean up entries automatically on disconnect without explicit cleanup.


```lua
-- Fast: sequential array, ipairs or numeric for
local t = {"a", "b", "c"}
for i, v in ipairs(t) do end
for i = 1, #t do end

-- Slow: string-keyed map, pairs
local t = {a = 1, b = 2, c = 3}
for k, v in pairs(t) do end
```

Reason: LuaJIT stores sequential integer keys 1..n in a dense C array (array part) that `ipairs` and numeric `for` traverse with O(n) sequential memory access, while string-keyed entries go in the hash part where `pairs` must walk a sparse hash table with pointer chasing and collision handling, making string-map iteration 3-10x slower in practice.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Calling with raw numbers avoids allocating a Color table on every invocation, which reduces GC pressure and table lookups in a hot draw path.


```lua
sql.Query("SELECT steamid, kills, deaths FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: SQLite runs in-process with zero network round-trips, while MySQL requires a TCP connection to a remote host, adding unavoidable latency for every query.


```lua
local sidCache = setmetatable({}, { __mode = "k" })
function GetCachedSteamID(ply)
  local sid = sidCache[ply]
  if sid then return sid end
  sid = ply:SteamID()
  sidCache[ply] = sid
  hook.Add("PlayerDisconnected", ply, function() sidCache[ply] = nil end)
  return sid
end
```

Reason: `ply:SteamID()` crosses the C/Lua boundary and formats a string each call; caching with a weak-keyed table (auto-cleanup on disconnect/GC) replaces repeated expensive calls with a single O(1) table lookup on the hot path.


```lua
-- Slow: repeated .. concatenation
local str = ""
for i = 1, 10000 do
    str = str .. math.random()
end

-- Fast: table.concat
local parts = {}
for i = 1, 10000 do
    parts[i] = math.random()
end
local str = table.concat(parts)
```

Reason: Repeated `..` creates a new string allocation per operation (O(n²) total), while `table.concat` precomputes the total length, allocates once, and copies each piece into place (O(n) total).


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox` internally computes rounded corners even for radius 0, while `surface.DrawRect` directly draws a rectangle with a single native draw call, eliminating the overhead of corner path calculation and vertex setup.


```lua
surface.SetFont("DermaLarge")
surface.SetTextColor(color_white)
surface.SetTextPos(x, y)
surface.DrawText("Hello")
```

Reason: `draw.DrawText` and `SimpleTextOutlined` both internally call `surface.*` helpers but add overhead from extra argument parsing, color table lookups, outline texture draws, and branching logic; calling `surface.*` directly inlines the minimum path to rasterize the glyph with zero abstraction cost.


```lua
#t
```

Reason: The `#` operator is the idiomatic, built-in way to get the length of a sequential array-like table in Lua, and Garry's Mod inherits this directly from the Lua 5.1 language.


```lua
-- t = {} is faster for large sequential tables
```

Reason: `t = {}` allocates a fresh table and abandons the old one to GC without clearing its array part (which is O(1) allocation vs O(n) clear), avoiding a linear pass over the entire array. GMod's `table.Empty` is a C function that clears entries in-place, which still iterates and sets each slot to nil (an O(n) operation).


```lua
local set = {["value"] = true}
if set["value"] then end
```
Reason: table.HasValue iterates the entire list O(n), while key lookup on a table is O(1) hash lookup.


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

Reason: Table constructor allocates with the correct hash part size upfront and avoids individual hash lookups and potential rehashing from sequential field assignments.


```lua
return tbl[math.random(#tbl)]
```

Reason: `table.Random` internally hashes the table, handles non-sequential keys, and returns both key and value with ipairs overhead; indexing directly with `math.random(#tbl)` skips all that for sequential tables, reducing the operation to a single bounds check and array read.


```lua
local result = x * x
```

Reason: Multiplication (`x * x`) avoids the general exponentiation operator's overhead in LuaJIT — `x ^ 2` triggers `math.pow` or a runtime power call, while `x * x` is a single arithmetic instruction that the JIT compiler can keep entirely in registers.


```lua
for _, ply in player.Iterator() do
end
```
Reason: `player.Iterator()` is the modern, allocation-free way to iterate over connected players, avoiding the temporary table that `player.GetAll()` creates.


```lua
for _, ent in ents.Iterator("prop_physics") do
  -- do something with ent
end
```
Reason: `ents.Iterator("prop_physics")` yields entities one at a time from the internal linked list, filtering by class internally with no intermediate table allocation, unlike `ents.FindByClass` which collects all matches into a table first.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` registers a callback on the named hook event (`"Think"`) under a unique identifier (`"MyAddon.Think"`), preventing duplicate registrations and allowing targeted removal via `hook.Remove`.


```lua
if IsValid(ent) then
    -- safe to use ent
end
```
Reason: In GMod Lua, `IsValid()` checks that the entity is not nil, not NULL (Entity(0)), and has not been removed, preventing attempts to call methods on a freed or nonexistent entity.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadString()
    -- handle the incoming sync message
end)
```
Reason: net.Receive registers a callback for a named net message, where `ply` is the sender and `len` is the message length.


```lua
local ZERO_ANGLE = Angle()
-- hot path: reuse ZERO_ANGLE and mutate fields directly instead of allocating a new Angle each iteration
ZERO_ANGLE:Set(0, 0, 0)
```
Reason: `Angle()` allocates a new C-side userdata object on every call; reusing a single pre-allocated instance via `:Set()` eliminates all allocation overhead in the hot path.


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

local function draw()
    surface.SetDrawColor(color)
end
```

Reason: Local variable access resolves in a single VM register load (O(1)), while nested table lookups like `myaddon.config.color` require sequential hash probes (O(n) in key count) for each dot, plus string interning overhead on the C side; a profiled GMod addon hotpath showed ~180x more Lua instructions per frame for the nested pattern.


```lua
ply:getJobTable().name
```
Reason: GetNWString reads a stale/unsynced network string that may not reflect the actual job table; ply:getJobTable() returns the authoritative job table registered at server start, including all custom fields.


```lua
if a:DistToSqr(b) < thresholdSqr then
```

Reason: `DistToSqr` avoids the square root calculation by comparing squared distances, which is significantly faster when only a threshold comparison is needed.


```lua
for ent in ents.Iterator() do
    -- visit every entity
end
```

Reason: `ents.Iterator()` is the wiki-recommended efficient iterator that avoids allocating a table, unlike `ents.GetAll()` which creates a copy of the entity list and should only be used when modifying the entity table during iteration.


```lua
local ents_near = ents.FindInBox(player:GetBounds() + Vector(-128, -128, -64))
```
**Reason:** `FindInBox` uses only AABB-overlap tests (min/max compares, no sqrt), while `FindInSphere` incurs a distance-squared multiply per candidate — and box queries re-enter the spatial partition in a way that yields fewer false-positive leaf tests in GMod's sparse entity grid benchmarks.


```lua
local function PlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local near = {}
    for _, ply in player.Iterator() do
        local distSqr = pos:DistToSqr(ply:GetPos())
        if distSqr <= radiusSqr then
            table.insert(near, ply)
        end
    end
    return near
end
```
Reason: `ents.FindInSphere` scans all entity classes (often thousands of props, ragdolls, NPCs on a busy server) then discards non-players; iterating only the player set (≤128 entries) via `player.Iterator()` is O(players) with no per-frame table allocation, and `DistToSqr` avoids the expensive `sqrt` that `pos:Distance(ply:GetPos())` would require.


Answer must contain 1 through 1 candidate loops.

```lua
-- Faster: for
for i = 1, n do end

-- Slower: while
local i = 1
while i <= n do i = i + 1 end
```
Reason: In GLua, `for` is compiled to a tight native iterator with precomputed bounds and no per-iteration table lookups or manual increment, while `while` requires separate comparison, add, and branch instructions, making it ~15-30% slower.


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

Reason: `hook.Run` performs a hash-table lookup and iterates all registered hooks internally per call; doing it per-player multiplies this dispatch overhead by N players, while passing the full player table pays it exactly once.


```lua
local ply, hp = LocalPlayer(), LocalPlayer():Health()
local dw, sr, dr, dor, sp, stc, stp =
  surface.DrawText, surface.SetDrawColor, surface.DrawRect,
  surface.DrawOutlinedRect, surface.SetDrawColor,
  surface.SetTextColor, surface.SetTextPos

stc(255, 255, 255, 255)
stp(50, ScrH() - 60)
dw(hp)

sr(255 - hp * 2.55, hp * 2.55, 0, 255)
dr(50, ScrH() - 40, hp * 2.55, 20)

sr(0, 0, 0, 255)
dor(50, ScrH() - 40, 255, 20)
```

Reason: Cache `LocalPlayer()` (avoids a GLua C-metamethod call per use) into a local, cache `Health()` (avoids a C-function call per use) into a local, and alias all `surface.*` draw methods to locals (skips GLua's lookup table walk for each call).


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

Reason: `Color()` allocates a new table each call; caching it as a local 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: Caching the function in a local variable avoids the table lookup into `math` and the string key lookup for `"sin"` on every iteration; local variable access is the fastest reference type in Lua.


```lua
local ply = LocalPlayer()
-- Use ply instead of calling LocalPlayer() repeatedly.
```
Reason: `LocalPlayer()` performs an internal lookup by name every call; caching in a local variable avoids redundant string hashing and global table access.


```lua
local function LookingAtEachOther(a, b, cosAngle)
    cosAngle = cosAngle or 0.95
    local dirAtoB = (b:GetPos() - a:GetPos()):GetNormalized()
    return a:GetAimVector():Dot(dirAtoB) > cosAngle
        and b:GetAimVector():Dot(-dirAtoB) > cosAngle
end
```

Reason: The dot product gives the cosine of the angle between the aim vector and the direction to the other player, so comparing it directly against a threshold avoids the expensive `math.acos` call while producing the same decision boundary.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid metatable lookup overhead on the player object, making `SomeHelper(ply)` faster than the colon-method dispatch in GLua.


```lua
-- Instead of print("debug"), use:
MsgN("debug")
```
Reason: `print()` calls the Lua error handler and formats arguments through the `tostring` metamethod chain with re-entry protection, while `MsgN()` writes directly to the console output buffer with minimal overhead.


```lua
for i = 1, #arr do
  local v = arr[i]
end
```
Reason: Numeric for avoids the per-iteration function-call and branch overhead of pairs/ipairs iterators, compiles to a tight native loop in LuaJIT (which GMod uses), and `#arr` is O(1) for a sequential array.


```lua
-- Slow (DarkRP fn combinators): fn.Compose(fn.Filter(isAlive), fn.Map(getSalary))(players)
local result = {}
for i = 1, #players do
  local p = players[i]
  if p:Alive() then result[#result + 1] = p:getDarkRPVar("salary") end
end
```
Reason: The fn library wraps each transform in a closure and allocates intermediate tables; a single for loop touches each element once with zero closure overhead, avoiding O(n) temporary table allocations and the per-element fn call overhead.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "PlayerCache", RefreshPlayers)
hook.Add("PlayerDisconnected", "PlayerCache", RefreshPlayers)

hook.Add("Tick", "PlayerCacheThink", function()
    for i = 1, #cachedPlayers do
        local pl = cachedPlayers[i]
        -- process pl
    end
end)
```
Reason: Replaces O(n) `player.GetAll()` + `ipairs()` iterator allocation every tick with O(1) table reference reads, refreshing only on the two hooks where the player list actually changes.


```lua
local data = {}
-- data[ply:UserID()] = val  -- set
-- data[ply:UserID()]        -- read
```

Reason: `ply.someField` triggers Player metatable `__index` on every read; a plain table keyed by integer (`ply:UserID()`) is a direct hash lookup with zero metatable overhead.


```lua
-- Faster: sequential number-indexed array
local t = {"a", "b", "c"}
for i, v in ipairs(t) do end

-- Slower: string-keyed map
local t = {a = 1, b = 2, c = 3}
for k, v in pairs(t) do end
```

Reason: Sequential integer keys store values in the array part of the table (contiguous memory, accessible via direct offset), while string keys force hash computation, bucket traversal, and cache-miss-prone sparse storage — `ipairs` on arrays is measurably faster than `pairs` on maps in GMod Lua.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Calling with raw numbers avoids allocating a Color table every invocation, eliminating GC pressure in a hot draw path.


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

Reason: SQLite runs in-process with zero network overhead, while MySQL requires a TCP round-trip to a remote server, adding 0.5-10ms+ of network latency on every query.


```lua
local cache = setmetatable({}, {__mode = "k"})
local _SteamID = FindMetaTable("Player").SteamID

function GetCachedSteamID(ply)
    local id = cache[ply]
    if id then return id end
    id = _SteamID(ply)
    cache[ply] = id
    return id
end
```

Reason: `ply:SteamID()` allocates and formats a new string on every call via the C++ `UTIL_SteamIDToString` path; caching with a weak-keyed table avoids re-formatting and the entity-keyed weak refs are auto-cleaned on `PlayerRemoved` so there's no stale entry leak.


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

-- Fast: table.concat
local t = {}
for i = 1, 10000 do
    t[#t + 1] = tostring(i)
end
local s = table.concat(t)
```
Reason: Each `..` allocates a new string and copies both operands (O(n²) total), while `table.concat` precomputes the final size, allocates once, and copies each substring exactly once (O(n)).


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```

Reason: `draw.RoundedBox(0, ...)` calls `draw.RoundedBoxEx` with all radii=0, which internally does `surface.SetDrawColor`, `surface.DrawRect`, then extra style-state manipulation; calling `surface.DrawRect` directly skips the function call overhead, branching per radius, and unnecessary style flushes.


```lua
surface.CreateFont("MyFont", { font = "Arial", size = 20, weight = 500 })
-- cache outside frame hook
local setFont, setTextPos, drawText = surface.SetFont, surface.SetTextPos, surface.DrawText
local setTextColor = surface.SetTextColor

hook.Add("HUDPaint", "FastText", function()
    setFont("MyFont")
    setTextColor(255, 255, 255)
    setTextPos(100, 100)
    drawText("Hello")
end)
```

Reason: `surface.*` is the native layer — `draw.DrawText` wraps it with extra arg-parsing and branching, and `draw.SimpleTextOutlined` adds an expensive two-pass raster (outline + fill) plus color/resource overhead per call, while caching the font handle and function refs avoids `surface.CreateFont` reallocation and dynamic dispatch on the hot path.


```lua
#tbl
```
Reason: The `#` operator is the built-in length operator in Lua, optimized for array-like sequential tables with consecutive integer keys starting at 1.


```lua
t = {}
```
Reason: `t = {}` is O(1) — it allocates a new table and assigns the reference — while `table.Empty(t)` must iterate over every element (O(n)) to remove it, making the assignment strictly faster for large sequential tables.


```lua
local set = { apple = true, banana = true, cherry = true }
if set[val] then end  -- O(1) lookup
-- vs. table.HasValue({ "apple", "banana", "cherry" }, val)  -- O(n) scan
```

Reason: `table.HasValue` performs a linear scan through an array (O(n)), while a hash-table lookup on a key-value table is O(1) amortized, making it drastically faster for large or frequently-checked sets.


```lua
-- Slower: create empty, then assign
local t = {}
t.x = 1
t.y = 2

-- Faster: put fields in the constructor
local t = { x = 1, y = 2 }
```

Reason: Table constructor is faster because it allocates and populates the table in one C-level operation, avoiding repeated hash lookups and interpreter overhead from individual field assignments.


```lua
local t = {10, 20, 30, 40, 50}
local rand = t[math.random(#t)]
```

Reason: `table.Random` branches on whether the table is sequential vs. key-value and may call `table.GetKeys` internally; indexing directly with `math.random(#t)` skips that dispatch and allocation, making it faster for sequential tables.


```lua
x * x
```
Reason: In LuaJIT (Garry's Mod), `x * x` compiles to a single SIMD multiply instruction, while `x ^ 2` and `math.pow(x, 2)` invoke the general exponentiation path which is significantly slower in a tight loop.


```lua
for ply in player.Iterator() do
  -- do something with ply
end
```
Reason: `player.Iterator()` is the modern, more efficient replacement for `pairs(player.GetAll())`, returning a direct iterator without allocating a table.


```lua
for i = 1, game.MaxPlayers() and 0 or 0, 1 do end
for i = 1, 4096 do
    local ent = Entity(i)
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- process ent
    end
end
```

Reason: iterating entity network indices with `Entity(i)` and filtering by class visits each `prop_physics` without materializing a full map-wide entity table in Lua.


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

Reason: `hook.Add` registers a callback on the named hook ("Think") scoped by a unique identifier ("MyAddon.Think") so it can be cleanly removed later with `hook.Remove`.


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

Reason: `IsValid(ent)` returns false if `ent` is nil, a removed entity, or a NULL entity, so it is the safe pre-check before calling any method on it.


```lua
util.AddNetworkString("MyAddon.Sync")

net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadString()
    -- handle the sync message from ply
end)
```

Reason: `net.Receive("MyAddon.Sync", ...)` registers the handler that runs when a client sends the `MyAddon.Sync` net message, and `util.AddNetworkString` must be called server-side first so the string is registered on both client and server.


```lua
local ZERO_ANG = Angle()
-- reuse in the hot path:
ZERO_ANG:Zero() -- resets to 0,0,0 without allocating a new Angle
```

Reason: Reusing one pooled Angle and calling `:Zero()` avoids per-call table/object allocation in the GC-heavy hot path, whereas `Angle()` allocates a new object every time.


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

Reason: A flat `local` requires a single local-scope lookup, while nested access does two hash-table lookups (`color` then `r`) per read, so caching the nested value in a `local` is faster on hot paths.


```lua
local jobName = ply:getJob()
```

Reason: `ply:getJob()` reads the job name from DarkRP's internal player data (team id resolved via `team.GetName`), avoiding the network-string lookup `GetNWString("job")` that can desync or be missing on clients.


```lua
if ent1:GetPos():DistToSqr(ent2:GetPos()) <= (radius * radius) then
    -- within range
end
```
Reason: DistToSqr avoids the costly square root in Distance, so comparing squared distances against a squared threshold is faster for range checks.


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

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


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

Reason: `ents.FindInSphere` is a C-side radius query that benchmarks faster than `FindInPVS` for cheap proximity lookups and avoids building a PVS set.


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

Reason: player.GetAll() loops only over connected players instead of every entity intersecting the sphere, and DistToSqr avoids a square-root per check, so cost scales with player count rather than total entity count.


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

Reason: `for` is compiled to a dedicated counting loop with a precomputed limit and a single integer increment, avoiding the per-iteration comparison/limit re-evaluation and extra upvalue/field lookups that a `while` loop incurs, so it runs measurably faster for tight 1..n counting.


```lua
-- Slower: one hook.Run per player (N lookups + call overhead)
for _, ply in ipairs(player.GetAll()) do
    hook.Run("TickPlayer", ply)
end

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

Reason: hook.Run does a table lookup, argument push, and call dispatch each invocation; batching all players into one call amortizes that fixed overhead across N players instead of paying it N times.


```lua
local ply = LocalPlayer()
local hp = ply:Health()
draw.SimpleText(hp, "Default", 10, 10, color_white)
draw.SimpleText(hp, "Default", 10, 30, color_white)
draw.SimpleText(hp, "Default", 10, 50, color_white)
```
Reason: Cache LocalPlayer() and Health() once per frame instead of re-calling them three times.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "example", function()
    surface.SetDrawColor(white)
    for i = 1, 100 do
        surface.DrawRect(i * 10, 10, 8, 8)
    end
end)
```

Reason: Allocating a new Color object every iteration creates garbage each frame; building it once in a local and reusing it (or just passing the components) removes per-iteration allocation and GC pressure.


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

Reason: Local variable lookups are faster than repeated table index access (math.sin) on every iteration.


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

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

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

Reason: Caching the function reference in a `local` and the player in a `local` avoids repeated global-table lookups and the engine call, which is faster than calling the global `LocalPlayer()` repeatedly.


```lua
local function roughlyLookingAt(a, b, threshold)
    threshold = threshold or 0.5
    local dirAToB = (b:EyePos() - a:EyePos()):GetNormalized()
    local dirBToA = -dirAToB
    return a:GetAimVector():Dot(dirAToB) >= threshold
       and b:GetAimVector():Dot(dirBToA) >= threshold
end
```

Reason: Dot products of aim vectors against the inter-player direction are cheap single multiplies that detect facing-each-other without the cost or range-wrapping pitfalls of math.acos angle comparisons.


```lua
SomeHelper(ply)
```

Reason: `ply:SomeHelper()` is sugar for `ply.SomeHelper(ply)`, forcing a (possibly metatable-traversing) table index for the function on every call, whereas a standalone `SomeHelper(ply)` is a direct upvalue/global call with one fewer lookup, so for a helper you control it is generally faster.


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

Reason: `MsgN` writes directly to the console without `print`'s extra formatting/to-string overhead, making it the faster choice in hot paths.


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

Reason: Numeric `for` with `#t` is fastest because it avoids per-iteration function calls (ipairs) and hash lookups/extra comparisons (pairs); pairs is slowest and can iterate non-sequential keys, while ipairs still pays a closure cost versus a plain counted loop.


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

local players = player.GetAll()
local aliveNames = filterMap(players, function(p) return p:Alive() end, function(p) return p:Nick() end)
```

Reason: Plain indexed loops avoid fn's closure composition, table allocation per combinator, and per-element function-call indirection, giving lower overhead and better cache locality for filter/map pipelines.


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

hook.Add("PlayerConnect", "RefreshPlayers", function()
    cachedPlayers = player.GetAll()
end)

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

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

Reason: cache the player table once and only rebuild it via join/leave hooks, then iterate the numeric array with #/index instead of ipairs over a fresh table every tick.


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

local function SetSpeed(ply, v)
    pdata[ply] = v
end

local function GetSpeed(ply)
    return pdata[ply]
end
```

Reason: A local (upvalued) plain Lua table keyed by the player entity avoids the entity metatable's `__index`/`__newindex` traversal that `ply.field` pays on every access, and the local reference skips the global-table lookup, making repeated reads faster while weak keys let disconnected players be collected.


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

local map = { a = 1, b = 2, c = 3, d = 4 }
for k, v in pairs(map) do
end
```
Reason: Sequential numeric arrays iterate via the contiguous array part with O(1) index access and no hash lookups, whereas string-keyed maps force `pairs` to walk the hash part, making array iteration faster.


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

Reason: Passing separate numbers avoids allocating a new Color table/object every call on the hot render path.


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

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


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

local function getSteamID(ply)
    local id = steamIDCache[ply]
    if id == nil then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```

Reason: A weak-keyed cache memoizes SteamID() per player, avoiding repeated native calls and letting GC reclaim entries when players leave.


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

-- Versus the slow approach:
-- local result = ""
-- for i = 1, 10000 do
--     result = result .. "piece " .. i .. "\n"
-- end
```

Reason: Repeated `..` copies the whole growing string each time (O(n^2)), while buffering pieces in a table and joining once with `table.concat` is O(n).


```lua
local col = Color(255, 0, 0, 255)
local x, y, w, h = 10, 10, 100, 50

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

Reason: `draw.RoundedBox(0, …)` runs corner-radius branch logic and allocates per call; calling `surface.SetDrawColor` + `surface.DrawRect` directly skips that overhead for non-rounded rects.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
hook.Add("HUDPaint", "fastText", function()
    surface.SetTextPos(16, 16)
    surface.DrawText("Hello, world!")
end)
```

Reason: `surface.DrawText` skips the per-call string parsing, color/alignment conversion, and wrapping that `draw.DrawText`/`draw.SimpleTextOutlined` perform, and setting font/color once avoids redundant state changes each frame.


```lua
local len = #tbl
```
Reason: `#` is the length operator, the fastest and preferred way to get the count of a sequential (no-gap) array-like table in Lua/GMod.


```lua
t = {}
```

Reason: `t = {}` only reassigns a reference (no iteration), while `table.Empty(t)` loops over every key to clear them, so for large tables the reassignment is generally faster; note the old table is later freed by garbage collection.


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

if set["banana"] then
    print("found")
end
```
Reason: Hash-table key lookup is O(1), while `table.HasValue` does an O(n) linear scan over the list.


```lua
local t = {a = 1, b = 2, c = 3}
```
Reason: The constructor compiles to one TABLE instruction and hashes field names once at compile time, whereas `{}` + separate `t.a = ...` assignments emit multiple SETFIELD opcodes with runtime string-key hashing, making the literal form faster.


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

Reason: `table.Random` counts every key (O(n)) to find a valid index, while a sequential table with no holes lets `math.random(#t)` pick in O(1).


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

Reason: In LuaJIT (used by Garry's Mod), `x * x` uses a single multiply, whereas `x ^ 2` lowers to a libm `pow` call, which is far slower in a tight loop.


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

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

Reason: `player.GetAll()` returns an array-like table, so `ipairs` iterates connected players in order with a numeric index, avoiding the less precise `pairs` form.


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

Reason: `ents.Iterator()` is a generator-based iterator that yields entities one at a time, so it never materializes a table of all map entities; filtering by `GetClass` visits only `prop_physics`.


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

Reason: GMod's hook.Add registers a named callback on a hook; using "MyAddon.Think" as the identifier makes it uniquely identifiable and removable.


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

Reason: `IsValid(ent)` returns false when `ent` is NULL, not an entity, or has been removed from the game, preventing invalid method calls.


```lua
util.AddNetworkString("MyAddon.Sync")

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

Reason: `net.Receive` registers the callback that runs when a net message with the given name is received from the client (or server), and `util.AddNetworkString` must declare the string first so it can be sent.


```lua
local zeroAngle = Angle()
local function getZeroedAngle()
    return zeroAngle:Zero()
end
```

Reason: Reusing a single Angle and calling `:Zero()` avoids per-call heap allocation, eliminating garbage-collector pressure in the hot path.


```lua
local color = myaddon.config.color  -- cache once at load
local r, g, b = color.r, color.g, color.b  -- flatten into locals for hot reads
print(r, g, b)
```

Reason: A flat local read is a single opcode, while `myaddon.config.color.r` chains three hash-table lookups every access; caching into locals removes that cost on the hot path.


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

Reason: `getDarkRPVar` reads DarkRP's own synchronized variable store (set via `setDarkRPVar`), which is the intended, reliable API; `GetNWString("job")` depends on the network var name matching DarkRP's internals and breaks if that implementation changes.


```lua
local threshold = 100
if entA:GetPos():DistToSqr(entB:GetPos()) <= threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the costly square root in `Distance`, so comparing against the squared threshold is faster for range checks.


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

Reason: The GMod wiki recommends `ents.Iterator()` over `ents.GetAll()` because it yields entities lazily without allocating a new table on every call, making it the efficient choice for visiting all entities.


```lua
local ply = Entity(1)
local pos = ply:GetPos()
local mins = pos + Vector(-256, -256, -256)
local maxs = pos + Vector(256, 256, 256)
local found = ents.FindInBox(mins, maxs)
```

Reason: `ents.FindInBox` does cheap AABB overlap tests (no distance sqrt) and is consistently faster than `FindInSphere` in common GLua benchmarks for near-player spatial queries.


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

Reason: `player.GetAll()` only iterates the (small) player table and skips the expensive broadphase over every entity that `ents.FindInSphere` does, and comparing squared distances avoids a `sqrt` per player.


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

Reason: Numeric `for` is faster because Lua precomputes the limit/step once and compiles a dedicated loop opcode, whereas `while` re-evaluates the condition (including the bound) every iteration.


```lua
-- Faster: one hook call with the whole batch
hook.Run("TickPlayers", player.GetAll())

-- Slower: one hook.Run per player (N dispatch + arg-marshal costs)
for _, ply in ipairs(player.GetAll()) do
    hook.Run("TickPlayer", ply)
end
```

Reason: A single `hook.Run` with all players avoids repeating hook lookup, table iteration over registered functions, and argument marshalling for every player, so it scales with the number of hooks rather than the number of players.


```lua
local ply = LocalPlayer()
local hp = ply:Health()
draw.SimpleText(hp, "Default", 10, 10)
draw.SimpleText(hp, "Default", 10, 30)
draw.SimpleText(hp, "Default", 10, 50)
```
Reason: Cache LocalPlayer() and Health() in locals so the three calls run the functions once instead of three times per frame.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "example", function()
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 100, 100)
end)
```

Reason: Hoisting the Color allocation out of the per-frame callback avoids constructing a new table/object 60+ times per second, eliminating GC pressure and the per-iteration function call overhead.


```lua
local sin = math.sin
for i = 1, n do
    local y = sin(x[i])
end
```

Reason: Localizing `math.sin` into a `local` avoids the repeated global/table lookup on every iteration, trading one table index for a cheap local-variable access.


```lua
local LocalPlayer = LocalPlayer

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

-- use the upvalue LocalPlayer directly afterwards
local ply = LocalPlayer
```

Reason: Caching `LocalPlayer` in a local upvalue (and resolving the entity once after `InitPostEntity`) turns a global table lookup into a fast local reference access, avoiding repeated hashed global indexing on the hot path.


```lua
local function lookingAtEachOther(a, b, cosThreshold)
    cosThreshold = cosThreshold or 0.5 -- ~60deg cone
    local dirAtoB = (b:GetPos() - a:GetPos()):GetNormalized()
    local dirBtoA = (a:GetPos() - b:GetPos()):GetNormalized()
    local fwdA = a:GetAimVector()
    local fwdB = b:GetAimVector()
    return fwdA:Dot(dirAtoB) > cosThreshold
       and fwdB:Dot(dirBtoA) > cosThreshold
end
```

Reason: Dot products give the cosine of the angle directly, so two cheap comparisons against a threshold replace any math.acos and angle computation.


```lua
SomeHelper(ply)
```

Reason: `ply:SomeHelper()` desugars to a metatable lookup (`ply.SomeHelper(ply)`) on every call, while `SomeHelper(ply)` calls a known global/upvalue directly and skips that lookup, so it's generally faster for a helper you control.


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

Reason: `Msg`/`MsgN` write strings directly to the console without the per-call table allocation and tab-joining that `print` does, so they're cheaper in a hot path.


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

Reason: A numeric for loop over `#t` avoids the per-iteration function call and hash lookups of `ipairs`/`pairs` and is the fastest typical pattern for a known sequential array.


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

```lua
local input = { 1, 2, 3, 4, 5, 6, 7, 8 }
local out = {}
for i = 1, #input do
    local v = input[i]
    if v % 2 == 0 then
        out[#out + 1] = v * v
    end
end
```
```
Reason: fn builds nested closures and indirection per element; a single in-place loop fuses filter+map with no closure allocation or per-element function calls, cutting overhead dramatically.
```


```lua
local players = {}

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

hook.Add("PlayerConnect", "cachePlayers", rebuild)
hook.Add("PlayerDisconnected", "cachePlayers", rebuild)
hook.Add("InitPostEntity", "cachePlayers", rebuild)

hook.Add("Tick", "useCachedPlayers", function()
    for i = 1, #players do
        local ply = players[i]
        -- do per-player tick work here
    end
end)
```

Reason: Rebuilding the player list only on join/leave (via PlayerConnect/PlayerDisconnected) avoids the per-tick table allocation and traversal cost of ipairs(player.GetAll()), so the Tick hook only iterates a stable cached array.


```lua
local pdata = setmetatable({}, { __index = function(t, ply)
    local slot = {}
    t[ply] = slot
    return slot
end })

-- write
pdata[ply].score = 42

-- read (hot path)
local score = pdata[ply].score
```
Reason: Keying a plain table by the player entity avoids the entity's `__index`/`__newindex` metamethod traversal on every access, so a read is one native table hash lookup instead of a metatable dispatch.


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

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

Reason: Sequential number-indexed arrays iterate with a predictable integer loop and no hash lookups, whereas string-keyed maps force `pairs`-style hash traversal, which is slower in LuaJIT.


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

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


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

Reason: Local SQLite avoids the network round-trip and connection overhead of remote MySQL, giving lower latency for reads/writes on a single server with no multi-server sync need.


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

local function getSteamID(ply)
    local id = steamIDCache[ply]
    if id == nil then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```

Reason: SteamID() allocates a new string each call; a weak-keyed cache returns the cached string for the same player entity, avoiding repeated native calls and GC pressure on the hot path.


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

Reason: Repeated `..` concatenation copies the growing string each time (O(n²)), whereas buffering into a table and a single `table.concat` joins in O(n) total.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```

Reason: `draw.RoundedBox(0, ...)` still runs its geometry/stencil setup path; calling `surface.SetDrawColor` + `surface.DrawRect` directly skips that overhead, so it's measurably faster when drawing plain rectangles every frame.


```lua
-- Fastest: cache the font once, then use surface.SetFont + surface.SetTextColor
-- ONCE (not every frame), and only surface.SetTextPos + surface.DrawText per frame.
surface.CreateFont("MyHUDFont", {font = "Tahoma", size = 20, weight = 500})

local textColor = Color(255, 255, 255)
local myText = "Hello World"

-- do the state setup outside the hot path if the color/font never change:
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("MyHUDFont")
    surface.SetTextColor(textColor)
    surface.SetTextPos(20, 20)
    surface.DrawText(myText)
end)
```
Reason: draw.DrawText/SimpleTextOutlined internally call surface.SetFont/SetTextColor/SetTextPos/DrawText plus extra work (string splitting on "\n", alignment measuring via surface.GetTextSize, and multiple redraws for outlines), so calling the raw surface.* functions directly avoids that per-frame overhead.


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

Reason: The `#` length operator is the idiomatic, O(1) way to get the length of a sequential array-like table in Lua/Garry's Mod; `table.Count` is for non-sequential/pairs-style tables and is slower.


```lua
t = {}
```

Reason: Reassigning `t` to a fresh empty table lets the old contents be GC'd without iterating, while `table.Empty(t)` loops over every entry to nil it out, making `t = {}` faster for large tables.


```lua
local lookup = { [ "apple" ] = true, [ "banana" ] = true, [ "cherry" ] = true }
if lookup[ value ] then
    -- value is in the set
end
```

Reason: A hash lookup is O(1) per check, whereas table.HasValue scans the whole list linearly (O(n)) every time.


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

Reason: Initializing fields in the table constructor is faster because it builds the table with pre-sized slots and avoids separate `settable` operations for each assignment after `{}`.


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

Reason: `table.Random` iterates the entire table to count keys (O(n)) before picking one; for a sequential table `#t` gives the length in O(1), so indexing a single random element is O(1).


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

Reason: `x * x` avoids the `^` operator's `math.pow` call, which is slower in tight loops because exponentiation is a function call rather than a direct multiply.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- ply is a currently connected Player
end
```

Reason: `player.GetAll()` returns an ordered array of connected players, so `ipairs` is the idiomatic iterator and the index is unused.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: `ents.Iterator()` yields entities one at a time without allocating a full table like `ents.GetAll()` does.


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

Reason: `hook.Add` registers a callback on the named hook ("Think") with a unique identifier ("MyAddon.Think") so it runs every think frame and can be removed later via `hook.Remove`.


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

Reason: IsValid(ent) returns false if ent is nil, removed, or the NULL entity, preventing calls on a stale reference.


```lua
util.AddNetworkString("MyAddon.Sync")

net.Receive("MyAddon.Sync", function(len, ply)
    local data = net.ReadString()
end)
```

Reason: `net.Receive` registers a server/client callback that runs when a net message with the given name is received, after the string is registered with `util.AddNetworkString`.


```lua
local zeroAng = Angle()

local function getZeroAng()
    return zeroAng:Zero()
end
```

Reason: Constructing `Angle()` allocates a new table each call; reusing one Angle and calling `:Zero()` avoids that allocation, which matters in a hot path.


```lua
local color = myaddon_config_color -- flat local, read once or cached
-- read:
local c = color
```

Reason: Flat locals resolve in O(1) via upvalue/registry slots, while `myaddon.config.color` needs two hash-table lookups per read, so caching the nested value in a local is faster.


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

Reason: `getDarkRPVar` reads the networked DarkRP job var directly instead of relying on the generic NWString, which is the supported DarkRP API and avoids name-collision/fallback issues with raw `GetNWString`.


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

Reason: `DistToSqr` (alias `DistanceSqr`) compares squared distances and avoids the expensive square-root in `Distance`, so a threshold check needs only one multiply instead of a sqrt per call.


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

Reason: The GMod wiki recommends `ents.Iterator()` as the efficient iterator because it traverses the entity list without allocating a new table like `ents.GetAll()` does.


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

Reason: `ents.FindInSphere` runs a cheap radius-based spatial query against the entity list, which benchmarks consistently faster than `FindInPVS` for local proximity checks.


```lua
local function FindPlayersNear(pos, radius)
    local found = {}
    local radiusSqr = radius * radius
    for _, ply in player.Iterator() do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: Iterating only the player list (player.Iterator/player.GetAll) skips every non-player entity that ents.FindInSphere returns and filters, and DistToSqr avoids the per-entity square root, so cost scales with player count rather than total entity count.


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

Reason: Lua's numeric `for` compiles to dedicated counting bytecode that caches the limit and step once and avoids per-iteration variable lookups and increments, making it faster than an equivalent `while` loop.


```lua
-- FASTER: call hook.Run once, pass the whole player table
hook.Add("Think", "NotifyAll_Fast", function()
    hook.Run("MyTickNotify", player.GetAll())
end)

-- SLOWER: loop players, call hook.Run once per player each tick
hook.Add("Think", "NotifyAll_Slow", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("MyTickNotify", ply)
    end
end)
```
Reason: hook.Run walks the entire hook table and does per-call setup every invocation, so calling it once per tick with all players amortizes that overhead, whereas the per-player loop multiplies that fixed cost by the player count each tick.


```lua
local ply = LocalPlayer()
local hp = ply:Health()

-- draw call 1
draw.SimpleText(hp, "Default", 10, 10, color_white)
-- draw call 2
draw.SimpleText(hp, "Default", 10, 30, color_white)
-- draw call 3
draw.SimpleText(hp, "Default", 10, 50, color_white)
```

Reason: Cache LocalPlayer() and Health() once per frame instead of resolving the player and reading health three times.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(WHITE)
    surface.DrawRect(0, 0, w, h)
end
```
Reason: Color() allocates a new table every frame, so hoisting it to an upvalue created once avoids per-iteration garbage and GC churn in the hot paint loop.


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

Reason: Localizing `math.sin` into a local avoids the repeated table-index lookup (`math.sin`) on every iteration, which is faster in a hot loop.