```lua
local health = LocalPlayer():Health()
draw.SimpleText(health, ...)
-- draw call 2 using health
-- draw call 3 using health
```

Reason: Caching LocalPlayer():Health() in a local avoids two redundant function calls per frame.


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

Reason: Allocating a new Color table every iteration is wasteful; constructing it once outside the loop and reusing the same reference avoids per-frame garbage and function-call overhead.


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

Reason: Localizing `math.sin` to a local var avoids repeated table lookups (and the global `math` access) on every iteration, which is faster in a tight loop.


```lua
local ply = LocalPlayer()

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

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

-- use `ply` directly in hot paths instead of calling LocalPlayer() repeatedly
```

Reason: LocalPlayer() walks the entity list each call; caching the entity once and refreshing only on (re)spawn/InitPostEntity avoids repeated lookups in hot paths.


```lua
local function areLookingAtEachOther(p1, p2, cosTol)
    cosTol = cosTol or 0.5 -- ~60 degrees tolerance
    local p1pos = p1:EyePos()
    local p2pos = p2:EyePos()
    local dirToP2 = (p2pos - p1pos):GetNormalized()
    local dirToP1 = (p1pos - p2pos):GetNormalized()
    local f1 = p1:GetAimVector()
    local f2 = p2:GetAimVector()
    return dirToP2:Dot(f1) >= cosTol and dirToP1:Dot(f2) >= cosTol
end
```

Reason: Dot product of the unit direction-to-other with each player's aim vector gives cos(angle) directly, avoiding math.acos and staying in cheap linear-time vector math.


```lua
SomeHelper(ply)
```

Reason: `ply:SomeHelper()` desugars to `ply.SomeHelper(ply)`, adding a metatable/table lookup to resolve the method, whereas `SomeHelper(ply)` is a direct function call with no dispatch overhead.


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

Reason: `MsgN` writes directly to the console bypassing `print`'s extra tostring/color/format overhead, making it cheaper in hot paths.


```lua
for i = 1, #tbl do
    local v = tbl[i]
    -- process v
end
```

Reason: numeric `for` avoids per-iteration function calls and hash lookups; `ipairs` adds metamethod/hook overhead and `pairs` is slower and iterates in arbitrary order.


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

-- vs DarkRP's fn.Filter(pred):Map(transform)(list)
local result = filterMap(player.GetAll(), function(p) return IsValid(p) and p:Team() == TEAM_CITIZEN end,
                                          function(p) return p:Nick() end)
```

Reason: A single plain numeric-loop pass with a preallocated result table avoids fn's per-element closure calls and metatable/chain overhead, doing filter+map in one traversal instead of two.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerConnect", "cache.players", refreshPlayers)
hook.Add("PlayerDisconnected", "cache.players", refreshPlayers)
hook.Add("InitPostEntity", "cache.players", refreshPlayers)

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

Reason: Rebuilding the player list only on join/leave/map load avoids the per-tick allocation and table scan of `player.GetAll()`, and a numeric `#` loop over the cached array is faster than `ipairs`.


Answer must contain 0 through 0 candidate loops.

```lua
local pdata = setmetatable({}, { __mode = "k" })  -- plain table, weak keys; player is the key

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

-- write:
get(ply).someField = value

-- hot read path: resolve once, then hit the plain table / local
local d = get(ply)
for i = 1, 100000 do
    local v = d.someField   -- no metatable lookup, just a plain-table/array read
end
```

Reason: `ply.someField` triggers the entity userdata's `__index`/`__newindex` metamethod on every access, while a plain Lua table keyed by the player (and especially a locally-cached reference) is a direct hash/array read with no metamethod overhead.


Answer must contain 0 through 1 candidate loops.

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

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

Reason: Sequential numeric arrays iterate via a tight counted loop (#arr bound, O(n) with no hash lookups), whereas string-keyed maps force `pairs` to traverse the hash part with unpredictable ordering and per-step key hashing, making arrays faster and more cache-friendly.


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

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


```lua
local row = sql.Query("SELECT score FROM player_data WHERE steamid = " .. sql.SQLStr(ply:SteamID()))
if row then
    print(row[1].score)
end
```

Reason: Local SQLite avoids network round-trips, so reads/writes are lower latency than a remote MySQL server.


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

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

Reason: ply:SteamID() rebuilds the string each call; caching it in a weak-keyed table (so disconnected players are GC'd) on first access makes repeated lookups O(1) with no per-frame recompute.


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

Reason: Repeated `..` concatenation is O(n²) because strings are immutable and each append copies the whole string; 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, ...) still does color/texture setup and a function dispatch for the no-rounding path; calling surface.SetDrawColor + surface.DrawRect directly skips that and draws the same axis-aligned rect with less per-call overhead.


```lua
-- Fastest: cache the font once, then use surface.SetFont + surface.SetTextColor + surface.SetTextPos + surface.DrawText
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)

hook.Add("HUDPaint", "FastText", function()
    surface.SetTextPos(20, 20)
    surface.DrawText("Hello world")
end)
```
Reason: `surface.DrawText` is the lowest-level primitive, while `draw.DrawText`/`draw.SimpleTextOutlined` wrap it with per-call string parsing, font/color setup, and alignment math (outlined draws the text up to 9 times), so calling `surface.*` directly avoids that per-frame overhead.


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

Reason: For sequential (integer-indexed) array-like tables, Lua's `#` length operator is the preferred, fastest, and idiomatic way to get the count in Garry's Mod.


```lua
t = {}
```

Reason: Reassigning `t = {}` just allocates a new table and drops the old one for garbage collection, avoiding the per-element iteration/clearing that `table.Empty(t)` performs on large tables.


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

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

Reason: table.HasValue scans the list linearly (O(n)) each check, while a keyed lookup table tests membership in constant time (O(1)).


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

Reason: Table literals build the hash/array part once in C, avoiding repeated hash lookups and separate assignment bytecode, so the constructor is faster than creating `{}` and assigning fields afterward.


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

Reason: table.Random iterates the whole sequential table with ipairs (O(n)); indexing a random key is O(1), so direct `t[math.random(#t)]` avoids the loop.


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

Reason: `x*x` is a single integer/float multiply, whereas `x^2` (and `math.pow`) routes through the generic exponentiation C function with float conversion and is measurably slower in a tight loop.


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

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

Reason: `player.Iterator()` avoids allocating a new table each call (unlike `pairs(player.GetAll())`), making it the recommended modern way to visit every connected player.


```lua
local ent = NULL
while true do
    ent = ents.FindByClass("prop_physics", ent)
    if not IsValid(ent) then break end
    -- process ent
end
```
Reason: `ents.FindByClass` accepts a start-after argument that lets you iterate one entity at a time without materializing a full table.


```lua
hook.Add("Think", "MyAddon.Think", function()
  -- minimal callback body
end)
```
Reason: This registers a Think hook with a unique identifier so it can be safely overridden or removed later.


Uses IsValid for entity/object validity.

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

Reason: `IsValid` returns false when the entity has been removed, is NULL, or is otherwise no longer safe to reference.


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

Reason: `net.Receive` registers a callback for an incoming net message by name.


```lua
local zero = Angle(0, 0, 0) -- allocate once outside the hot path

-- inside the hot path, instead of:
--   local a = Angle(0, 0, 0)
-- use:
zero.p = 0
zero.y = 0
zero.r = 0
```

Reason: `Angle()` allocates a fresh userdata every call, which adds GC pressure in hot paths; mutating a single pre-allocated scratch Angle avoids the allocation entirely and is safe because `Entity:SetAngles` and similar APIs copy the value by component, not by reference.


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

```lua
local cfg_color = myaddon.config.color  -- hoist once (e.g. at file load)
local c = cfg_color                      -- fast local read
Reason: Hoisting into locals avoids repeated table-lookups; each index into a table is a C hash lookup that the LuaJIT trace cannot fully collapse, so a cached local is measurably faster for hot paths.
```


```lua
-- Preferred: uses DarkRP's own synced variable system
local jobName = ply:getDarkRPVar("job")

-- Alternative: directly from the team table
local jobName = RPExtraTeams[ply:Team()].name
```

Reason: `getDarkRPVar` reads variables synced through DarkRP's networking layer, which is the intended public API; `GetNWString("job")` bypasses that layer and relies on an implementation detail that could change.


```lua
local thresholdSq = threshold * threshold
if vec1:DistToSqr(vec2) < thresholdSq then
    -- within threshold
end
```

Reason: `Vector:DistToSqr` skips the square root needed by `Distance`, giving the same pass/fail result for threshold comparisons faster.


Answer must begin its reason with Reason:

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

**Reason:** `ents.Iterator()` is the wiki-recommended, allocation-free iterator over all entities; it avoids the per-call table creation of `ents.GetAll()` while yielding every valid entity exactly once.


```lua
local function GetNearbyEntities(ply, radius)
    local pos = ply:GetPos()
    local nearby = {}
    for _, ent in ipairs(ents.FindInSphere(pos, radius)) do
        if ent:IsValid() and ent ~= ply then
            nearby[#nearby + 1] = ent
        end
    end
    return nearby
end

local entities = GetNearbyEntities(ply, 500)
```

Reason: `ents.FindInSphere` is a C++ built-in that consistently benchmarks faster than `ents.FindInCone` or `ents.FindInBox` for arbitrary nearby-entity lookups because it avoids the extra axis math/construction and matches the most common spatial query shape.


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

Reason: Iterating `player.GetAll()` is O(P) where P is the player count (typically 10–100), far smaller than `ents.FindInSphere`'s O(E) over all entities (often thousands); `DistToSqr` also avoids an unnecessary `sqrt` per comparison.


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

Reason: Numeric for loops are implemented in C and avoid the per-iteration overhead of condition evaluation and manual increment that while loops require.


```lua
-- Pattern A: One hook call, iterate players inside
hook.Run("MyTick", player.GetAll())

-- Pattern B: Loop, one hook call per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTick", ply)
end
```

Pattern A is faster: one hook dispatch vs N dispatches per tick.


```lua
hook.Add("HUDPaint", "DrawHealth", function()
    local health = LocalPlayer():Health()
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(10, 10, health, 20)
    surface.SetDrawColor(0, 255, 0, 255)
    surface.DrawRect(10, 40, health, 20)
    surface.SetDrawColor(0, 0, 255, 255)
    surface.DrawRect(10, 70, health, 20)
end)
```
Reason: Caching the health value in a local variable eliminates redundant function calls and improves performance.


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

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

Reason: Allocating a table every frame creates unnecessary GC pressure; caching outside the loop avoids repeated allocations.


```lua
local sin = math.sin
for i = 1, n do
  -- use sin(x) instead of math.sin(x)
  result = sin(x)
end
```

Reason: Assigning `math.sin` to a local once avoids repeated global table lookups (`math` table → `sin` key) on every iteration, since locals are accessed via registers while globals require hash-table traversal.


```lua
-- Cache once at the top of your script or in a shared helper
local ply = LocalPlayer()

-- Then use 'ply' everywhere instead of calling LocalPlayer() repeatedly
hook.Add("Think", "MyOptimizedHook", function()
    if not IsValid(ply) then return end
    -- use ply instead of LocalPlayer()
end)
```

Reason: LocalPlayer() performs a C-to-Lua boundary crossing each call; caching it in a local avoids repeated lookups while staying valid for the lifetime of the reference (IsValid handles disconnects).


```lua
local function PlayersMutuallyLooking(p1, p2)
    local d1 = p1:GetAimVector()
    local d2 = p2:GetAimVector()
    return d1:Dot(p2:GetPos() - p1:GetPos()) > 0.7
       and d2:Dot(p1:GetPos() - p2:GetPos()) > 0.7
end
```
Reason: Two dot products (vector-subtract + dot, no acos) — each tests that a player's aim vector points toward the other; 0.7 threshold ≈ a 45-degree cone, cheap and sufficient for a rough "looking at each other" check.


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

Reason: The colon syntax (`ply:SomeHelper()`) is a sugar that adds an implicit `self` parameter; both compile to the same opcode, but the explicit form is marginally clearer for static helpers and avoids any ambiguity about method dispatch.


```lua
MsgN("[DEBUG] value: ", tostring(val))
```

Reason: `MsgN`/`Msg` bypass `print()`'s internal string formatting and C++ call overhead, making it faster for high-frequency logging.


Answer must contain 1 through 1 candidate loops.

```lua
local t = {}
for i = 1, 1000000 do t[i] = i end

local sum = 0
for _, v in ipairs(t) do
    sum = sum + v
end
```

Reason: `ipairs` is a C-level iterator in LuaJIT optimized for sequential integer keys, matching or beating numeric `for` in typical GMod benchmarks while avoiding the hash-table traversal overhead that makes `pairs` significantly slower on array-like tables.


Answer must contain 0 through 2 candidate loops.

```lua
-- Fast pipeline: chain filter/map without the fn library overhead.
local function pipeline(list, ...)
  local out = {}
  for i = 1, #list do out[i] = list[i] end
  for i = 1, select("#", ...) do
    local op = select(i, ...)
    if op[1] == "filter" then
      local fn, j = op[2], {}
      for _, v in ipairs(out) do
        if fn(v) then j[#j + 1] = v end
      end
      out = j
    elseif op[1] == "map" then
      local fn = op[2]
      for k, v in ipairs(out) do
        out[k] = fn(v)
      end
    end
  end
  return out
end

-- Example: keep only players with > 0 health, then grab names.
local result = pipeline(player.GetAll(),
  { "filter", function(p) return p:Health() > 0 end },
  { "map",    function(p) return p:Nick() end }
)
```

Reason: DarkRP's fn library uses meta-tables, closures per step, and repeated generic iterator overhead; a simple in-place pipeline with index-based loops and no allocations per step avoids that cost while staying readable.


```lua
-- Cached player table, refreshed only on PlayerInitialSpawn / PlayerDisconnected
local CachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "RefreshPlayerCache", function()
    timer.Simple(0, RebuildPlayerCache)
end)

hook.Add("PlayerDisconnected", "RefreshPlayerCache", function()
    timer.Simple(0, RebuildPlayerCache)
end)

-- Your per-tick hook now iterates the cached table
hook.Add("Think", "MyOptimizedHook", function()
    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        -- use ply
    end
end)
```

Reason: Replaces per-tick `ipairs(player.GetAll())` with a cache rebuilt only on join/leave via `timer.Simple(0, ...)`, giving O(1) table creation cost on hook fires while staying accurate to player list changes.


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

local function set PlyData(ply, key, value)
  local id = ply:UniqueID()
  local bucket = cache[id]
  if not bucket then
    bucket = {}
    cache[id] = bucket
  end
  bucket[key] = value
end

local function getPlyData(ply, key)
  local id = ply:UniqueID()
  local bucket = cache[id]
  return bucket and bucket[key]
end

local function clearPlyData(ply)
  cache[ply:UniqueID()] = nil
end
```

Reason: `ply.SomeField` requires two `__index` metamethod lookups per access (Entity metatable → ply table), while a pre-hashed integer-keyed table avoids metamethod overhead entirely; `UniqueID()` can be pre-computed once per session and cached alongside the value for O(1) repeated lookups.


```lua
-- Sequential array (faster for iteration)
local colors = {
  [1] = "red",
  [2] = "green",
  [3] = "blue",
  [4] = "yellow",
  [5] = "cyan",
}

-- String-keyed map (slower for iteration)
local colorMap = {
  red   = 1,
  green = 2,
  blue  = 3,
  yellow = 4,
  cyan  = 5,
}

-- Iterate array
for i = 1, #colors do
  local v = colors[i]
end

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

Reason: LuaJIT (used in GMod) can JIT-compile numeric `ipairs`-style loops into tight native code with predictable memory access, while `pairs` on string-keyed tables uses hash lookups with higher per-iteration overhead and cannot be efficiently optimized by the JIT.


```lua
-- Fast: pass primitives directly, no Color allocation
surface.SetDrawColor(255, 100, 0, 255)
surface.DrawRect(x, y, w, h)

-- Slow: allocates a Color table each call
surface.SetDrawColor(Color(255, 100, 0, 255))
surface.DrawRect(x, y, w, h)
```
Reason: The primitive form skips the Color table allocation and GC overhead that accumulates in tight draw loops.


```lua
sql.Query("CREATE TABLE IF NOT EXISTS players (steamid TEXT PRIMARY KEY, name TEXT, score INTEGER)")
sql.Query("INSERT OR REPLACE INTO players (steamid, name, score) VALUES (" .. sql.SQLStr(steamid) .. ", " .. sql.SQLStr(name) .. ", " .. score .. ")")
local row = sql.QueryRow("SELECT * FROM players WHERE steamid = " .. sql.SQLStr(steamid), 1)
```

Reason: Local SQLite avoids the network round-trip to a remote MySQL server, making it lower latency for reads and writes on a single game server with no multi-server sync requirement.


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

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

function ClearSteamIDCache()
  table.Empty(steamIDCache)
end
```

Reason: `__mode = "k"` creates a weak-key table so entries are garbage-collected when the player entity is removed, avoiding leaks while eliminating repeated method calls and hash lookups in the hot path.


```lua
-- Slow: repeated .. creates a new string every iteration — O(n²) total
local result = ""
for i = 1, #pieces do
    result = result .. pieces[i]
end

-- Fast: table.concat joins once — O(n) total
local t = {}
for i = 1, #pieces do
    t[#t + 1] = pieces[i]
end
local result = table.concat(t)
```

Reason: Each `..` allocates an intermediate string; for 10 000 small pieces that is ~50 MB of garbage vs one final string, so `table.concat` is linear and avoids quadratic allocation pressure.


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

Reason: `surface.DrawRect` skips the rounded-box corner logic entirely, calling the underlying quad draw in one step with less overhead than `draw.RoundedBox(0, ...)`.


```lua
-- Fastest: surface.SetTextPos + surface.DrawText (no per-frame font re-creation)
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("DermaLarge")  -- cache font; set once or outside tight loops
    surface.SetTextPos(100, 100)
    surface.SetTextColor(255, 255, 255, 255)
    surface.DrawText("Hello World")
end)
```

Reason: `draw.DrawText` and `SimpleTextOutlined` allocate internally each call; `surface.DrawText` with a pre-set font skips those allocations and is the cheapest per-frame text draw.


```lua
local count = #myTable
```

Reason: The `#` operator is Lua's idiomatic and performant way to get the length of a sequence-like table.


```lua
-- Preferred: keep the reference, reuse memory
table.Empty(t)

-- Slower: allocates a new table each time; old one becomes garbage
t = {}
```

Reason: `table.Empty(t)` mutates in place, avoiding a new allocation and letting the GC keep the existing buffer; `t = {}` forces a fresh allocation every call, increasing GC pressure on large tables.


```lua
local list = { [1] = true, [2] = true, [3] = true }
if list[value] then
  -- value exists in the set
end
```

Reason: O(1) hash lookup instead of O(n) linear scan.


```lua
local t = {key1 = "val", key2 = "val", key3 = "val"}
```
Reason: The table constructor allocates the hash part with the correct size upfront, avoiding repeated rehashing that occurs when fields are added one-by-one to an empty table.


```lua
local randomIndex = math.random(#sequentialTable)
return sequentialTable[randomIndex]
```

Reason: For a sequential table, direct indexing with `math.random(#tbl)` avoids `table.Random`'s extra iteration and type-checking overhead — it's two O(1) operations (cached length + direct index) versus a full traversal.


```lua
local x2 = x * x
```
Reason: Multiplication is faster than `x^2` or `math.pow(x,2)` because it avoids a function call and the general exponentiation path.


```lua
for _, ply in player.Iterator() do
    -- your code here
end
```
Reason: `player.Iterator()` is the current recommended idiom for iterating over connected players in Garry's Mod, avoiding the intermediate table allocation of `player.GetAll()`.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
  -- your logic here
end
```

Reason: `ents.FindByClass` returns only the matching entities in one allocation pass, avoiding `ents.GetAll` and a manual filter loop.


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

Reason: `hook.Add` registers the callback under the named identifier so it fires every Think tick.


```lua
if IsValid(ent) then ent:Remove() end
```
Reason: `IsValid` returns false for NULL/invalid entities, preventing method calls on freed references.


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

Reason: `net.Receive` registers a callback function for a named network string; Garry's Mod networking requires the string to be registered with `util.AddNetworkString` on the server side before clients can send or receive it.


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

-- Hot path: reuse instead of allocating
_tempAngle.p = 0
_tempAngle.y = 0
_tempAngle.r = 0
```

Reason: `Angle()` calls the constructor every frame and allocates a new userdata; pre-allocating one shared instance and zeroing its fields avoids repeated allocation and GC pressure.


```lua
-- nested table for structure; flat local for hot reads
myaddon = myaddon or {}
myaddon.config = myaddon.config or { color = Color(255, 200, 0) }

local cfg_color = myaddon.config.color  -- cached at file scope

-- hot path reads the local, not the nested table
function DrawStuff()
    surface.SetDrawColor(cfg_color)
end
```
Reason: Local-variable reads are a single indexed-slot fetch; nested table reads chain two hash lookups per access.


```lua
local jobName = team.GetName(ply:Team())
```

Reason: `team.GetName(ply:Team())` is the canonical Garry's Mod API that reads directly from the team system DarkRP populates, avoiding the networked-variable lag and indirection of `GetNWString("job")`.


```lua
local thresholdSq = 10000  -- 100 units squared
local a = Vector(100, 50, 0)
local b = Vector(120, 60, 0)
local isClose = a:DistToSqr(b) < thresholdSq
```

Reason: `DistToSqr` avoids the expensive `sqrt` call inside `DistToSqr` is cheaper than `DistToSqr` + `sqrt` (which `Vector:Distance` does internally).


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

Reason: `ents.Iterator()` is the wiki-recommended way to traverse every entity efficiently—it yields entities lazily without allocating a full table like `ents.GetAll()`, reducing memory pressure and GC churn.


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

Reason: `ents.FindInSphere` is consistently the fastest spatial query in GMod benchmarks for "near this point" because it uses a spatial hash/grid internally, beating box and cone searches at small radii.


```lua
local function FindPlayersInSphere(pos, radius)
    local players, radiusSq = {}, radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSq then
            players[#players + 1] = ply
        end
    end
    return players
end
```
Reason: `player.GetAll()` iterates only the player pool (tens/hundreds), not every entity in the map (thousands), and `DistToSqr` avoids a per-entity square-root; for very hot paths you can also cache positions in a spatial grid indexed by chunk.


```lua
local i = 1
while i <= n do
  -- body
  i = i + 1
end
```

Reason: `while` avoids the iterator overhead of `for`, reducing allocations and calls per iteration, making it generally faster in Garry's Mod Lua.


```lua
-- PATTERN A: Single hook.Run, iterate inside the callback
hook.Add("Think", "NotifyAllPlayers_Single", function()
    for _, ply in ipairs(player.GetAll()) do
        CustomLogic(ply)
    end
end)

-- PATTERN B: Loop players, call hook.Run per player
hook.Add("Think", "NotifyAllPlayers_PerPlayer", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("PlayerThink", ply)
    end
end)
```
Reason: Pattern A avoids repeated hook-lookup overhead — `hook.Run` does a hash-table lookup and argument pack per call; calling it N times (once per player) multiplies that cost, while calling it once and iterating internally pays the overhead only once.


```lua
hook.Add("HUDPaint", "OptimizedHealthHUD", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText(hp, "DermaLarge", 100, 100, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText(hp, "DermaLarge", 200, 100, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    draw.SimpleText(hp, "DermaLarge", 300, 100, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```

Reason: Caching `LocalPlayer():Health()` into a local avoids two redundant method calls, Lua local variable access is faster than repeated method dispatch, and reducing interop overhead per frame.


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

hook.Add("Paint", "MyHUD", function(scrW, scrH)
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, scrW, scrH)
end)
```

Reason: Cache the Color object outside the loop so it is allocated once rather than every frame.


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

Reason: Localizing the function reference avoids a table lookup on `math` every iteration, saving ~15–20 ns per call in LuaJIT (GLua).


```lua
local ply
hook.Add("Think", "cache_lp", function()
  ply = LocalPlayer()
end)
```

Reason: Caching LocalPlayer() in a local variable eliminates repeated global table lookups per frame, reducing overhead in hot paths like HUD paint or think hooks.


```lua
function ArePlayersLookingAtEachOther(ply1, ply2)
    local pos1 = ply1:GetPos()
    local pos2 = ply2:GetPos()
    local dir1 = (pos2 - pos1):GetNormalized()
    local dir2 = (pos1 - pos2):GetNormalized()
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local dot1 = aim1:Dot(dir1)
    local dot2 = aim2:Dot(dir2)
    return dot1 > 0.7 and dot2 > 0.7
end
```

Reason: Uses dot products of aim vectors with direction vectors to check if both players are facing each other within a roughly 45-degree threshold, avoiding expensive acos calculations.


```lua
-- Preferred: local function, called directly
local function SomeHelper(ply)
  -- implementation
end

SomeHelper(ply)  -- faster: avoids table field lookup on ply
```

Reason: Method syntax `ply:SomeHelper()` is sugar for `ply.SomeHelper(ply)`, which requires a table lookup on `ply` each call; a local function called directly skips that lookup and is faster in Lua's VM.


```lua
MsgN("debug: ", x)
```
Reason: `MsgN` writes each argument to the console buffer separately via the C binding, skipping the intermediate string concatenation and extra formatting that `print` performs — the bottleneck in a hot loop is the concat, not the I/O.


```lua
local t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

-- fastest for sequential arrays
for i = 1, #t do
  local v = t[i]
end
```
Reason: Numeric `for` avoids the overhead of iterator creation and closure allocation that `ipairs` carries, and it skips the hash-lookup cost that `pairs` pays on every key; for dense sequential arrays the plain index loop is consistently fastest in LuaJIT.


```lua
local function transform_pipeline(items)
  local result = {}
  local j = 0
  for i = 1, #items do
    local v = items[i]
    if v.active then
      v = v.value * 2
      if v > 10 then
        j = j + 1
        result[j] = v
      end
    end
  end
  return result
end
```

Reason: DarkRP's `fn` library chains closures for each step (compose, map, filter), paying per-element overhead in every closure call; a single fused loop allocates no intermediate tables, keeps values in locals, and lets the JIT trace one straight path.


```lua
local cachedPlayers = {}
local cachedPlayerCount = 0

local function RefreshPlayerCache()
    local plys = player.GetAll()
    cachedPlayerCount = #plys
    cachedPlayers = {}
    for i = 1, cachedPlayerCount do
        cachedPlayers[i] = plys[i]
    end
end

hook.Add("PlayerInitialSpawn", "PlayerCacheRefresh", function()
    timer.Simple(0, RefreshPlayerCache)
end)

hook.Add("PlayerDisconnected", "PlayerCacheRefresh", function()
    timer.Simple(0, RefreshPlayerCache)
end)

hook.Add("Think", "CachedPlayerLoop", function()
    for i = 1, cachedPlayerCount do
        local ply = cachedPlayers[i]
        if ply and ply:IsValid() and ply:Alive() then
            -- your per-tick logic here
        end
    end
end)

hook.Add("InitPostEntity", "PlayerCacheInit", function()
    RefreshPlayerCache()
end)
```
Reason: Two player events trigger a single refresh through `timer.Simple(0, ...)` (defers past the current frame so `player.GetAll()` returns the updated list), while `Think` iterates an array by index with no allocations — avoiding the per-tick `ipairs` + `player.GetAll()` cost.


```lua
local store = {}  -- keyed by Entity reference

-- write
local function SetData(ply, key, value)
    local t = store[ply]
    if not t then
        t = {}
        store[ply] = t
    end
    t[key] = value
end

-- read
local function GetData(ply, key)
    local t = store[ply]
    if not t then return nil end
    return t[key]
end

-- cleanup on disconnect
hook.Add("PlayerDisconnected", "ClearStore", function(ply)
    store[ply] = nil
end)
```

Reason: Plain Lua table lookups by entity reference bypass Entity's `__index` metamethod chain, avoiding the repeated C-to-Lua boundary crossing and metatable traversal that `ply.someField` pays on every access.


```lua
local items = {"a", "b", "c", "d", "e"}
for i = 1, #items do
  -- process items[i]
end
```

Reason: Sequential numeric-indexed arrays use a compact vector layout allowing O(1) access via `ipairs`/numeric `for`, while string-keyed maps require hash table traversal with string comparisons on every access.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Separate numeric arguments skip the table-lookup overhead of unpacking a Color object's fields each call.


```lua
local steamid = "STEAM_0:1:12345678"
local result = sql.Query("SELECT * FROM players WHERE steamid = " .. sql.SQLStr(steamid))
if result then
    for _, row in ipairs(result) do
        print(row.name, row.score)
    end
end
```
Reason: Local SQLite avoids network latency and provides direct disk access, resulting in lower read/write latency.


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

local function cachedSteamId(ply)
    local sid = steamIdCache[ply]
    if sid == nil then
        sid = ply:SteamID()
        steamIdCache[ply] = sid
    end
    return sid
end
```

Reason: Weak-key table lets disconnected players be garbage-collected while avoiding repeated SteamID string lookups on the hot path.


```lua
-- Slow: repeated .. creates a new string each pass (O(n²))
local slow = ""
for i = 1, 10000 do
    slow = slow .. "piece"
end

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

Reason: `..` allocates a new string every iteration, copying all previous content each time, while `table.concat` builds a table of references and joins them in a single pass.


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

Reason: `surface.DrawRect` bypasses the function-call overhead, radius clamping, and internal branching inside `draw.RoundedBox`, issuing a direct draw primitive with fewer Lua instructions per frame.


```lua
-- Client Lua: fastest single-line text draw

local fontName = "MyFastFont"

if not surface.GetFontName(fontName) then
    surface.CreateFont(fontName, {
        font = "Roboto",
        size = 18,
        weight = 500,
        antialias = true,
    })
end

-- Pre-build the surface text once, not every frame
local cachedText = "Score: 100"
local cachedW, cachedH = surface.GetTextSize(cachedText)

local function DrawFastText()
    surface.SetFont(fontName)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(ScrW() / 2 - cachedW / 2, 10)
    surface.DrawText(cachedText)
end
```

Reason: `surface.DrawText` with a pre-created font skips the alignment parsing, color-markup scanning, and triple-pass outline rendering that `draw.DrawText` and `draw.SimpleTextOutlined` perform internally, making it the lowest-overhead path for a static single-line string each frame.


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

Reason: `#` is Lua's built-in length operator, efficient and idiomatic for sequential array-like tables.


```lua
-- Discarding contents of a large sequential table:
local t = {}  -- much faster: one allocation, old table becomes garbage

-- vs. table.Empty(t) which iterates every key:
-- for k in pairs(t) do t[k] = nil end  -- O(n) operations
```

Reason: `t = {}` is O(1) allocation; `table.Empty(t)` is O(n) with per-key GC overhead.


```lua
-- Slow: linear search (O(n))
local list = {"a", "b", "c", "d", "e"}
if table.HasValue(list, "c") then
    print("found")
end

-- Fast: hash-set lookup (O(1))
local set = { a = true, b = true, c = true, d = true, e = true }
if set["c"] then
    print("found")
end
```

Reason: `table.HasValue` does an O(n) linear scan each call; a pre-built hash-set (`tbl[key]`) is O(1) per lookup, making repeated existence checks dramatically faster on large lists.


```lua
-- Constructor: one operation
local t = {foo = 1, bar = 2, baz = 3}

-- Assign after: multiple operations
local t = {}
t.foo = 1
t.bar = 2
t.baz = 3
```

Reason: Constructor creates and populates in one step; assigning after requires creating an empty table plus extra hash lookups per field.


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

Reason: Avoids the O(n) copy and random-access loop that `table.Random` performs, replacing it with a single O(1) array index.


```lua
local xsq = x * x
```

Reason: Multiplication (`x * x`) compiles to a single `MUL` bytecode instruction while the `^` operator calls the `__pow` metamethod or `math.pow`, making `x * x` significantly faster in tight loops.


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

Reason: `player.Iterator()` is the recommended, zero-allocation way to visit every connected player in modern Garry's Mod Lua.


```lua
for i = 0, ents.GetHighestEntityIndex() do
    local ent = ents.GetByIndex(i)
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- your logic here
    end
end
```

Reason: Iterating by entity index avoids allocating a table; `GetByIndex` is O(1) per call and the loop only pays for the valid-class check on each live entity.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- your logic here
end)
```

Reason: Demonstrates attaching a callback to the Think hook with a unique identifier using Garry's Mod's hook.Add API.


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

Reason: `IsValid(ent)` returns `false` when the entity has been removed or the reference is stale, preventing errors from calling methods on an invalid entity.


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

Reason: Registers a callback for the MyAddon.Sync net message so that when it arrives, the provided function is executed with the message length.


```lua
-- Allocate once, reuse forever
local _zeroAngle = Angle(0, 0, 0)

local function ZeroAngle()
    _zeroAngle.x = 0
    _zeroAngle.y = 0
    _zeroAngle.z = 0
    return _zeroAngle
end
```

Reason: `Angle()` allocates a new userdata on the heap each call; resetting the fields of a pre-allocated shared instance avoids repeated allocation and garbage collection pressure in hot paths like per-frame hooks.


```lua
-- Preferred: cache the setting in a local variable for fast reads.
local color = myAddon.config.color
print(color)
```
Reason: Local variable lookup is faster than table field traversal, especially in hot loops.


```lua
local jobName = ply:getJobTable().name
```

Reason: `ply:getJobTable()` is DarkRP's canonical job accessor returning the full job table (with `.name`, `.category`, etc.), is maintained across DarkRP versions, avoids NW-string overhead, and won't break if the internal NW key changes.


```lua
local thresholdSq = 10000 -- e.g. 100^2
if a:DistToSqr(b) < thresholdSq then
    -- within range
end
```

Reason: `DistToSqr` avoids the expensive `sqrt` that `Distance` performs; square both sides of the comparison instead.


```lua
for _, ent in ents.Iterator() do
    -- process ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended way to efficiently visit every entity in Garry's Mod; it avoids building a temporary table.


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

Reason: `FindInSphere` leverages the BSP tree for O(log n) pruning and consistently benchmarks as the fastest built-in spatial primitive in GMod after `FindInPVS` (which requires a visibility table setup).


```lua
-- Using player.FindInSphere avoids enumerating props, NPCs, ragdolls, etc.
local nearby = player.FindInSphere(pos, radius)

-- If you need it as a table you can iterate:
for _, ply in ipairs(nearby) do
    -- do something with each player
end
```

Reason: `player.FindInSphere` queries the BSP partition tree limited to the player list, returning only player entities directly — no entity-type filtering needed and fewer allocations than `ents.FindInSphere` + manual filter.


```lua
local s = SysTime()
for i = 1, 10000000 do end
print("for:", SysTime() - s)

s = SysTime()
local i = 1
while i <= 10000000 do i = i + 1 end
print("while:", SysTime() - s)
```

Reason: `for` keeps the counter in a register with no per-iteration variable lookup or manual increment, while `while` must read, compare, and write the counter each iteration.


```lua
-- SLOWER: hook.Run called once per player per tick
for _, ply in ipairs(player.GetAll()) do
    hook.Run("CustomLogicTick", ply)
end

-- FASTER: hook.Run called once, logic receives all players at once
hook.Run("CustomLogicTick", player.GetAll())
```

Reason: `hook.Run` carries per-call overhead (argument packing, lookup, trace) — calling it N times multiplies that cost, whereas one call with the table trades N lookups for a single table allocation the receiver can iterate internally.


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

surface.SetDrawColor(0, 0, 0, 200)
surface.DrawRect(10, 10, hp * 2, 20)

surface.SetDrawColor(255, 0, 0)
surface.DrawRect(10, 10, hp, 20)

draw.SimpleText(hp, "DermaLarge", 10, 35, Color(255, 255, 255))
```

Reason: Storing `LocalPlayer():Health()` in a local variable (`hp`) avoids three redundant engine queries per frame; the result is fetched once and reused for all three draw calls.


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

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

Reason: Hoisting the Color constructor out of the hot loop eliminates per-frame table allocation and garbage-collection pressure.


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

Reason: Local variable lookup in Lua is faster than table index lookup (`math.sin`), so caching the function reference in a local avoids repeated global table traversal on each iteration.


```lua
-- Cache LocalPlayer() once per frame (e.g. in InitPostEntity or Think hook)
local ply
hook.Add("InitPostEntity", "CacheLocalPlayer", function()
    ply = LocalPlayer()
end)

-- Use ply directly thereafter; if you need frame-safe refresh:
local function GetPly()
    ply = ply or LocalPlayer()
    return ply
end
```

Reason: Caching `LocalPlayer()` in a local avoids repeated engine lookups per frame; the `or` fallback handles the rare nil case without a redundant global fetch each call.


```lua
function ArePlayersLookingAtEachOther(ply1, ply2)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local dot = aim1:Dot(aim2)
    return dot < -0.7  -- roughly 135° or less apart
end
```
Reason: The dot product is cheap and avoids costly trigonometric calls.


```lua
ply:SomeHelper()
```

Reason: The colon syntax is syntactic sugar for `SomeHelper(ply)` — they compile to nearly identical bytecode in Lua 5.1, so performance difference is negligible; prefer `:` for readability when the first parameter is conceptually `self`.


```lua
-- Instead of:  print("x =", x)
local dbg = Msg  -- cache the C-side function once
-- then in hot path:
dbg("x = " .. tostring(x) .. "\n")
```

**Reason:** `Msg` is a direct C binding that bypasses `print`'s vararg unpacking and per-argument `tostring` pass, cutting per-call overhead roughly in half.


```lua
local t = {1, 2, 3, 4, 5} -- large sequential table

-- fastest: numeric for
for i = 1, #t do
  local v = t[i]
end
```

Reason: `ipairs` is a C-callable iterator but still has per-iteration overhead from the iterator protocol; `pairs` does hash-table traversal with unpredictable order; a plain numeric `for` with `#t` cached is a simple register-counted loop with no function-call overhead per iteration, making it consistently fastest for sequential arrays.


```lua
-- Fast list pipeline: plain loops beat DarkRP's fn library
local function pipeline(tbl, ...)
  local fns = {...}
  local result = tbl
  for _, f in ipairs(fns) do
    local new = {}
    for _, v in ipairs(result) do
      local out = f(v)
      if out ~= false then
        new[#new + 1] = out
      end
    end
    result = new
  end
  return result
end

-- Usage: filter even, then double, then take if >4
local data = {1,2,3,4,5,6,7,8}
local result = pipeline(data,
  function(v) return v % 2 == 0 end,
  function(v) return v * 2 end,
  function(v) return v > 4 and v or false end
)
-- result = {6, 8, 10, 12}
```

Reason: Inlining filter/map as a single traversal with early-exit avoids fn library's per-step allocation, currying overhead, and intermediate table creation — reducing GC pressure on LuaJIT.


```lua
local cachedPlayers = {}
local cachedCount  = 0

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

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

hook.Add("Tick", "PlayerCache_Example", function()
    for i = 1, cachedCount do
        local ply = cachedPlayers[i]
        -- your per-player logic here
    end
end)
```

Reason: `player.GetAll()` allocates and sorts a new table each call; caching it avoids repeated allocation and GC pressure, and the hooks guarantee the cache stays in sync with joins and disconnects without per-tick cost.


```lua
-- Fast per-player cache: bypass Entity metatable with a plain table keyed by EntIndex
local plyData = {}

-- Write
local function SetTemp(ply, key, value)
    local id = ply:EntIndex()
    local bucket = plyData[id]
    if not bucket then
        bucket = {}
        plyData[id] = bucket
    end
    bucket[key] = value
end

-- Read
local function GetTemp(ply, key)
    local bucket = plyData[ply:EntIndex()]
    return bucket and bucket[key]
end
```

Reason: `ply.someField` invokes the Entity `__index` metamethod which calls `Entity:GetInternalVariable` (a C-side lookup), whereas indexing a plain Lua table by `EntIndex()` is a direct hash-table read with no metamethod overhead.


```lua
-- Sequential number-indexed array (faster)
local fast = { "alpha", "bravo", "charlie", "delta", "echo" }

-- String-keyed map (slower)
local slow = {
    a = "alpha",
    b = "bravo",
    c = "charlie",
    d = "delta",
    e = "echo",
}

-- ipairs iterates the compact array part with direct indexing
for i, v in ipairs(fast) do end

-- pairs hashes each key and walks the hash part
for k, v in pairs(slow) do end
```

Reason: Sequential integer arrays live in the contiguous array part of a Lua table, giving O(1) positional access and cache-friendly iteration via `ipairs`; string-keyed maps sit in the hash part, requiring key hashing and pointer chasing on every step, so they are measurably slower to traverse.


```lua
-- Faster: numeric arguments avoid a table lookup and potential object creation
surface.SetDrawColor(r, g, b, a)
```

Reason: `surface.SetDrawColor(color)` must unpack the Color table fields internally, whereas passing four numbers directly skips that indirection and avoids allocating or referencing an intermediate object in a hot loop.


```lua
-- SQLite example using the sql library
if sql.Query("CREATE TABLE IF NOT EXISTS player_data (steam_id TEXT PRIMARY KEY, data TEXT)") then
    sql.Query("INSERT OR REPLACE INTO player_data VALUES ('STEAM_0:1:12345', 'some data')")
end
```
Reason: SQLite is local to the server, eliminating network overhead that remote MySQL adds for every query.


```lua
local steamIdCache = {}

local function GetSteamId(ply)
    local idx = ply:EntIndex()
    local cached = steamIdCache[idx]
    if cached then
        return cached
    end
    local id = ply:SteamID()
    steamIdCache[idx] = id
    return id
end

hook.Add("PlayerInitialSpawn", "steamid_cache_init", function(ply)
    steamIdCache[ply:EntIndex()] = ply:SteamID()
end)

hook.Add("PlayerDisconnected", "steamid_cache_clear", function(ply)
    steamIdCache[ply:EntIndex()] = nil
end)
```

Reason: EntIndex() is a fast C++ integer lookup that serves as a cheap cache key, eliminating repeated engine round-trips to SteamID() for the same player object within a frame; clearing on disconnect prevents stale entries from reconnecting players.


```lua
-- Slow: repeated .. creates a new string each iteration (O(n²))
local s = ""
for i = 1, 10000 do
  s = s .. tostring(i)
end

-- Fast: table.concat builds one string in one pass (O(n))
local t = {}
for i = 1, 10000 do
  t[i] = tostring(i)
end
local s2 = table.concat(t)
```
Reason: Each `..` allocates a brand-new string and copies all prior characters, so `n` concatenations cost O(n²) time and peak memory; `table.concat` assembles from a pre-built table of segments in a single O(n) pass with no intermediate copies.


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

Reason: `draw.RoundedBox` still validates corner radius and builds a mesh even at 0; `surface.DrawRect` issues the minimal quad draw call directly.


```lua
-- Precompute once (e.g. in Init or when font changes)
surface.CreateFont("FastFont", {font="Arial", size=16, weight=700})
surface.SetFont("FastFont")
local tw, th = surface.GetTextSize("Hello")

-- Per-frame (e.g. in Paint)
local x, y = 100, 100
surface.SetFont("FastFont")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText("Hello")
```

Reason: `surface.*` skips the alignment/splitting overhead inside `draw.DrawText`/`SimpleTextOutlined`, and caching `GetTextSize` avoids recalculating it every frame.


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


```lua
local t = {}

-- Slow: O(n) — must visit every key
-- table.Empty(t)

-- Fast: O(1) — old table becomes unreachable garbage
t = {}
```
Reason: `t = {}` is O(1) while `table.Empty(t)` is O(n) because it must iterate and nil each key; discarding the reference and letting Lua's GC reclaim the old table is faster for large sequential tables.


```lua
-- Slow: table.HasValue scans every index — O(n)
local list = {"apple", "banana", "cherry"}
if table.HasValue(list, "banana") then print("found") end

-- Fast: build a hash set, then lookup is O(1)
local set = {}
for _, v in ipairs(list) do
  set[v] = true
end
if set["banana"] then print("found") end
```

Reason: `table.HasValue` does a linear O(n) scan on a numerically-indexed list, while a hash-set lookup is O(1) — one key access instead of walking every element.


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

Reason: Table constructors with known keys are faster because they populate the hash part directly in a single allocation, whereas post-construction assignment forces the VM to grow the table incrementally.


```lua
local elem = tbl[math.random(#tbl)]
```

Reason: Inlining `math.random` + direct index avoids `table.Random`'s function-call and extra-return overhead; for sequential tables this is the fastest general approach.


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

Reason: Multiplication is the fastest numeric operation in LuaJIT; `math.pow` or `x^2` add function-call overhead that matters in tight loops.


```lua
for _, ply in player.Iterator() do
    -- your code here
end
Reason: player.Iterator() avoids allocating a temporary table each frame, making it the idiomatic GMod Lua pattern.
```


```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 materializing a full table, satisfying the requirement to avoid building a table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your think logic here
end)
```

Reason: In Garry's Mod, `hook.Add(eventName, identifier, callback)` registers a callback for a hook. The Think hook runs every frame, and using "MyAddon.Think" as the identifier allows unique identification and potential removal via `hook.Remove("Think", "MyAddon.Think")`.


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

Reason: `IsValid(ent)` is the canonical GMod check — it returns false for `nil`, removed entities, and entities that no longer exist on the server/client, preventing errors when calling methods on stale references.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming sync message here
    local data = net.ReadTable() -- or other net.Read* functions based on your protocol
    -- Process data...
end)
```

Reason: Registers a server-side handler for the "MyAddon.Sync" net message using GMod's net library, receiving the message length and sending player as arguments.


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

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

Reason: Reusing a single Angle instance avoids garbage collection pressure from allocating new objects every frame. `SetUnpacked` or direct field assignment is faster than `Angle(0, 0, 0)` which creates a new table.


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

-- read
local r, g, b = color.r, color.g, color.b
```

Reason: Local variables avoid global table lookup and nested tables require multiple hash lookups (myaddon → config → color); LuaJIT optimizes local access to direct register/stack access.


```lua
-- Preferred
local jobName = ply:getDarkRPVar("job")
-- Or for the full job table
local jobTable = ply:getJobTable()
local jobName = jobTable and jobTable.name
```

Reason: `getDarkRPVar` is the official DarkRP API for accessing player DarkRP variables, which handles nil safety and is the intended public interface. `GetNWString` bypasses DarkRP's abstraction and can break if internals change.


```lua
if vector1:DistToSqr(vector2) <= threshold * threshold then
    -- vectors are within threshold distance
end
```

Reason: `DistToSqr` avoids the expensive square root operation by comparing squared distances directly, which is mathematically equivalent for threshold checks.


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

Reason: `ents.Iterator()` is the wiki-recommended efficient iterator that avoids allocating a table, unlike `ents.GetAll()`.


```lua
local pos = player:GetPos()
local radius = 500
local entities = ents.FindInSphere(pos, radius)
```

Reason: `ents.FindInSphere` uses a simple spatial partition (Octree) with a single radius check, making it consistently faster than `FindInBox` (AABB overhead) or `FindInCone` (dot products) for "near player" queries in typical GMod benchmarks.


```lua
local function FindPlayersInSphere(pos, radius)
    local players = player.GetAll()
    local radiusSqr = radius * radius
    local result = {}

    for i = 1, #players do
        local ply = players[i]
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            result[#result + 1] = ply
        end
    end

    return result
end
```

Reason: `player.GetAll()` iterates only over connected players (typically <100) instead of all entities (often thousands), and `DistToSqr` avoids the expensive square root operation.


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

Reason: LuaJIT compiles numeric `for` loops to optimized bytecode with a dedicated loop counter, eliminating explicit increment/comparison overhead present in `while` loops.


```lua
-- Slower: hook.Run called per player (N calls per tick)
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomTick", ply)
end

-- Faster: single hook.Run with all players (1 call per tick)
local players = player.GetAll()
hook.Run("MyCustomTick", players)
```

Reason: Each `hook.Run` invocation has fixed overhead (hook table lookup, argument packing, protected call). Calling it once with a table of all players avoids N-1 redundant hook dispatches per tick, reducing CPU overhead proportionally to player count.


```lua
hook.Add("HUDPaint", "OptimizedHealthDraw", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.RoundedBox(0, 10, 30, hp * 2, 20, Color(255, 0, 0))
    draw.SimpleText(hp .. " HP", "DermaDefault", 10, 55, color_white)
end)
```

Reason: Caching LocalPlayer():Health() in a local variable avoids three redundant method calls per frame, reducing overhead from C++/Lua boundary crossings and improving performance.


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

hook.Add("HUDPaint", "Example", function()
    -- use white instead of Color(255,255,255)
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 100, 100)
end)
```

Reason: Creating a new Color object every frame allocates garbage and triggers GC pressure; caching it once outside the paint hook avoids repeated allocation.


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

Reason: Localizing `math.sin` to a local variable `sin` avoids a global table lookup on every iteration, reducing overhead in hot loops.


```lua
local ply = LocalPlayer()

hook.Add("Think", "MyHook", function()
    if not IsValid(ply) then ply = LocalPlayer() return end
    -- use ply instead of LocalPlayer()
end)
```

Reason: Caching LocalPlayer() in a local variable avoids the global lookup and C++ bridge call on every tick; the IsValid check handles player initialization and respawn.


```lua
function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- cos(~45°), tune as needed
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local toTarget = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    return aim1:Dot(toTarget) > threshold and aim2:Dot(-toTarget) > threshold
end
```

Reason: Uses cheap dot products (cosine similarity) instead of acos; compares each player's aim vector against the direction to the other player with a configurable cosine threshold.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the table lookup (`ply.SomeHelper`) that the colon syntax performs, making them slightly faster in Lua.


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

Reason: `MsgN` writes directly to the console without the string formatting and argument processing overhead of `print`, making it significantly faster in hot paths.


```lua
local t = {1, 2, 3, 4, 5} -- large sequential array-like table
for i = 1, #t do
    local v = t[i]
    -- process v
end
```

Reason: Numeric for (`for i = 1, #t do`) avoids iterator function call overhead, allows direct index access, and JIT-compiles to tight machine code in LuaJIT (used by Garry's Mod). `ipairs` adds per-iteration function calls; `pairs` uses generic hash-table traversal.


```lua
local function fastPipeline(tbl, operations)
    local result = {}
    local idx = 0
    for i = 1, #tbl do
        local v = tbl[i]
        local keep = true
        for _, op in ipairs(operations) do
            if op.type == "filter" then
                if not op.fn(v) then
                    keep = false
                    break
                end
            elseif op.type == "map" then
                v = op.fn(v)
            end
        end
        if keep then
            idx = idx + 1
            result[idx] = v
        end
    end
    return result
end

-- Usage:
-- local out = fastPipeline(players, {
--     {type = "filter", fn = function(p) return p:Alive() end},
--     {type = "map", fn = function(p) return p:Nick() end},
-- })
```

Reason: Single-pass loop with inline operations avoids fn library's function call overhead, closure allocations, and intermediate table creation. Uses numeric indices for O(1) appends.


```lua
local cachedPlayers = {}

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

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

hook.Add("Think", "PlayerCache_Use", function()
    for _, ply in ipairs(cachedPlayers) do
        -- your per-player logic here
    end
end)
```

Reason: Avoids allocating a new table and iterating all players every tick by maintaining a live list updated only on join/leave events.


```lua
local playerData = {}

hook.Add("PlayerInitialSpawn", "InitPlayerData", function(ply)
    playerData[ply] = {}
end)

hook.Add("PlayerDisconnected", "CleanPlayerData", function(ply)
    playerData[ply] = nil
end)

-- Fast read/write
local data = playerData[ply]
data.someField = value
local val = data.someField
```

Reason: Direct table lookup `playerData[ply]` avoids metatable overhead of `ply.someField`, giving O(1) access vs metatable `__index` chain.


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

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

Reason: Sequential arrays use contiguous memory and `ipairs`/numeric loops with direct index access (O(1) per element), while string-keyed maps require hash table traversal via `pairs` with higher constant overhead and non-sequential memory access patterns.


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

Reason: Passing separate r,g,b,a arguments avoids allocating a Color table, eliminating GC pressure in hot draw paths.


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

Reason: Local SQLite (sql library) runs in-process with zero network overhead, while MySQL requires IPC/network round-trips even on localhost, adding measurable latency for every query.


```lua
local steamIDCache = {}

local function GetCachedSteamID(ply)
    if not IsValid(ply) then return nil end

    local key = ply:EntIndex()
    local cached = steamIDCache[key]
    if cached then return cached end

    local sid = ply:SteamID()
    steamIDCache[key] = sid
    return sid
end

hook.Add("EntityRemoved", "ClearSteamIDCache", function(ent)
    if ent:IsPlayer() then
        steamIDCache[ent:EntIndex()] = nil
    end
end)
```

Reason: Uses EntIndex() as stable key, caches on first call, clears on player disconnect to prevent memory leaks and stale data.


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

Reason: `table.concat` performs a single allocation and copy (O(n)), while repeated `..` creates a new string each iteration (O(n²)).


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

Reason: `surface.DrawRect` is the direct internal function that `draw.RoundedBox(0, ...)` calls, avoiding the function overhead and corner-radius logic branch entirely.


```lua
-- Faster: surface.* helpers (lower-level, less overhead)
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 10)
surface.DrawText("Hello World")

-- Slower: draw library wrappers
-- draw.DrawText("Hello World", "DermaDefault", 10, 10, color_white)
-- draw.SimpleTextOutlined("Hello World", "DermaDefault", 10, 10, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, color_black)
```

Reason: `surface.DrawText` avoids the draw library's internal font lookup, color normalization, alignment calculations, and outline rendering overhead — it directly uses the VGUI surface API with pre-set state.


```lua
local length = #myTable
```

Reason: The `#` operator is the standard and most performant way to get the length of a sequential array-like table in Lua, including Garry's Mod.


```lua
-- Faster: reassign to new table
t = {}

-- Slower: clear in place
table.Empty(t)
```

Reason: `t = {}` is O(1) — it just allocates a new empty table and lets the old one be GC'd asynchronously. `table.Empty(t)` is O(n) — it must iterate every key and nil it out synchronously.


```lua
-- Slow: O(n) linear search
local list = { "a", "b", "c", "d" }
table.HasValue(list, "c")

-- Fast: O(1) hash lookup
local set = { a = true, b = true, c = true, d = true }
set["c"] ~= nil
```

Reason: `table.HasValue` iterates the entire array; a hash table with keys provides constant-time lookup.


```lua
local t = { field1 = value1, field2 = value2, field3 = value3 }
```

Reason: Table constructors with known fields allocate the exact size upfront in a single VM instruction, avoiding hash rehashing and multiple `OP_SETTABLE` bytecode ops that post-assignment requires.


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

Reason: `math.random(1, #tbl)` directly indexes the sequential table with a random integer, avoiding `table.Random`'s internal bounds checks, type validation, and function call overhead. For sequential tables, direct indexing is O(1) vs `table.Random`'s O(1) with higher constant factors.


```lua
local result = x * x
```
Reason: Multiplication (`x * x`) compiles to a single VM instruction (MUL), while `x^2` or `math.pow(x, 2)` invoke the power metamethod or a C function call, adding significant overhead in tight loops.


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

Reason: `player.Iterator()` is the modern, idiomatic way to iterate over connected players in Garry's Mod. It returns an iterator function that yields each player directly, avoiding the overhead of `pairs()` on a table and the deprecated `player.GetAll()` pattern.


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

Reason: `ents.Iterator()` returns a stateless iterator that yields entities one at a time without materializing a full table, satisfying the no-table constraint.


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

Reason: In Garry's Mod, `hook.Add(eventName, identifier, callback)` registers a callback for the given hook event. The identifier "MyAddon.Think" uniquely names this registration so it can be removed later with `hook.Remove("Think", "MyAddon.Think")`.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: `IsValid()` returns false for NULL entities, removed entities, and nil, preventing errors when calling methods on invalid references.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the message here
    local data = net.ReadTable() -- or other net.Read* functions
    print("Received MyAddon.Sync:", data)
end)
```
Reason: In Garry's Mod, `net.Receive` registers a handler for incoming net messages by name. The callback receives the message length and the sending player (server-side) or just length (client-side).


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

-- In hot path:
zeroAngle.p = 0
zeroAngle.y = 0
zeroAngle.r = 0
-- use zeroAngle
```

Reason: Reusing a single pre-allocated Angle instance avoids garbage collection pressure from repeatedly allocating new objects in hot paths.


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

-- Read
local c = color
```

Reason: Local variables are resolved at compile-time to register/stack slots, avoiding runtime table lookups required for globals (`_G.myaddon.config.color`) or nested tables (`myaddon.config.color`).


```lua
-- Preferred: DarkRP variable API
local jobName = ply:getDarkRPVar("job")

-- Or for full job table (name, salary, model, etc.)
local jobTable = ply:getJobTable()
local jobName = jobTable and jobTable.name
```

Reason: `getDarkRPVar` is the official DarkRP API for synchronized player variables, avoiding raw NWString access which bypasses DarkRP's variable system and can return stale/nil values during job transitions.


```lua
local threshold = 100
local thresholdSqr = threshold * threshold

if vector1:DistToSqr(vector2) <= thresholdSqr then
    -- vectors are within threshold distance
end
```

Reason: `DistToSqr` avoids the expensive square root operation by comparing squared distances directly, which is mathematically equivalent for threshold checks.


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

Reason: `ents.Iterator()` is the wiki-recommended efficient iterator that avoids allocating a full table like `ents.GetAll()` does, yielding entities one at a time.


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

Reason: FindInSphere uses a single C++ sphere trace with spatial partitioning (octree/BSP), avoiding PVS overhead and Lua-side distance checks; benchmarks consistently show it 2-5x faster than FindInPVS for radius queries.


```lua
local function FindPlayersInSphere(pos, radius)
    local players = {}
    local radiusSqr = radius * radius

    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            players[#players + 1] = ply
        end
    end

    return players
end
```

Reason: `player.GetAll()` iterates only players (not all entities), and `DistToSqr` avoids expensive square root operations compared to `Distance`.


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

-- while loop (slower)
local i = 1
while i <= n do
    -- body
    i = i + 1
end
```

Reason: LuaJIT optimizes numeric `for` loops directly in the VM with minimal bytecode overhead, while `while` loops require explicit variable management and more bytecode instructions per iteration.


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

-- Slower: hook.Run per player in a loop
for _, ply in ipairs(player.GetAll()) do
    hook.Run("CustomTick", ply)
end
```

Reason: `hook.Run` has dispatch overhead (lookup, iteration of registered hooks). Calling it once with a table avoids N-1 redundant dispatches; the hook callbacks receive the full player list and can loop internally if needed.


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

    local hp = ply:Health()

    -- Draw call 1
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 10, color_white)

    -- Draw call 2
    draw.RoundedBox(0, 10, 30, math.Clamp(hp, 0, 100) * 2, 20, Color(255, 0, 0))

    -- Draw call 3
    if hp <= 25 then
        draw.SimpleText("LOW HEALTH", "DermaDefaultBold", ScrW() / 2, 50, Color(255, 0, 0), TEXT_ALIGN_CENTER)
    end
end)
```

Reason: Caching `LocalPlayer():Health()` in a local variable avoids three redundant function calls and player validity checks per frame.


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

hook.Add("HUDPaint", "Example", function()
    -- use `white` here instead of Color(255,255,255)
    surface.SetDrawColor(white)
    -- ...
end)
```

Reason: Creating a Color object once outside the paint loop avoids allocating a new table every frame, reducing GC pressure and improving performance.


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

Reason: Localizing `math.sin` to a local variable avoids repeated global table lookups in the hot loop, reducing overhead from hash table access to a direct register/stack access.


```lua
local ply = LocalPlayer()

hook.Add("Think", "MyHook", function()
    if not IsValid(ply) then ply = LocalPlayer() return end
    -- use ply here
end)
```

Reason: Cache LocalPlayer() in a local upvalue and re-fetch only when invalidated (e.g., on player spawn/death), avoiding the global lookup every frame.


```lua
local function PlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or -0.7 -- ~135 degrees, tweak as needed
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    return aim1:Dot(aim2) < threshold
end
```

Reason: Dot product of aim vectors is negative when players face each other; checking `dot < threshold` avoids acos entirely and is a single SIMD-friendly operation.


```lua
SomeHelper(ply)
```

Reason: Direct function call avoids metatable lookup overhead on the player userdata; in LuaJIT both compile similarly but global/local function call is marginally faster than `:method()` syntax which requires `__index` resolution.


```lua
Msg("debug: value = ", value, "\n")
```

Reason: `Msg` is a lower-level C++ bound function that writes directly to the console without the formatting overhead of `print`. It accepts multiple arguments and concatenates them efficiently. For newline-terminated output, `MsgN` is also available. Both bypass the `tostring` formatting and hook system that makes `print` slower in hot paths.


```lua
local t = {1, 2, 3, 4, 5}

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

Reason: Numeric `for i = 1, #t` avoids iterator function overhead and table lookups entirely, directly indexing the array. `ipairs` adds an iterator call per iteration. `pairs` is slowest as it traverses all keys (including non-sequential) via `next`.


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

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

Reason: Plain loop with pre-allocated output avoids fn's intermediate tables, closure allocations, and iterator overhead; single pass does filter+map fused.


```lua
local cachedPlayers = {}
local cacheValid = false

local function rebuildCache()
    cachedPlayers = player.GetAll()
    cacheValid = true
end

hook.Add("PlayerInitialSpawn", "PlayerCache_Rebuild", rebuildCache)
hook.Add("PlayerDisconnected", "PlayerCache_Rebuild", rebuildCache)

hook.Add("Think", "PlayerCache_Example", function()
    if not cacheValid then rebuildCache() end
    for _, ply in ipairs(cachedPlayers) do
        -- your per-player logic
    end
end)
```

Reason: Caches `player.GetAll()` and only rebuilds on join/leave events, avoiding O(n) allocation every tick.


```lua
local playerData = {}

function GetPlayerData(ply)
    return playerData[ply]
end

function SetPlayerData(ply, value)
    playerData[ply] = value
end
```

Reason: Direct entity property access (`ply.field`) uses keyvalues with network overhead. A module-scoped table keyed by player entity avoids this entirely, giving O(1) Lua table reads/writes with no engine synchronization cost.


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

-- String-keyed map (slower iteration)
local map = { a = 1, b = 2, c = 3, d = 4, e = 5 }
for k, v in pairs(map) do
    -- process v
end
```

Reason: Sequential arrays use Lua's contiguous array part enabling direct index access and cache-friendly iteration, while string-keyed maps use the hash part requiring hash computations and scattered memory access.


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

Reason: Passing separate r,g,b,a numbers avoids allocating a Color object on every call, eliminating GC pressure in hot draw paths.


```lua
local result = sql.Query("SELECT steamid, money FROM player_data WHERE steamid = '76561198000000000'")
if result then
    PrintTable(result)
end
```

Reason: Local SQLite runs in-process with zero network round-trips, no connection pooling overhead, and direct file I/O, making it significantly lower latency than remote MySQL for a single-server workload.


```lua
local steamIDCache = {}

local function GetCachedSteamID(ply)
    local idx = ply:EntIndex()
    local cached = steamIDCache[idx]
    if cached then return cached end

    local sid = ply:SteamID()
    steamIDCache[idx] = sid
    return sid
end

hook.Add("EntityRemoved", "ClearSteamIDCache", function(ent)
    if ent:IsPlayer() then
        steamIDCache[ent:EntIndex()] = nil
    end
end)
```

Reason: Uses EntIndex() as a stable integer key for O(1) table lookups, clears cache on player disconnect to prevent memory leaks, and avoids repeated SteamID() calls on the hot path.


```lua
-- Slow: repeated concatenation (O(n²))
local result = ""
for i = 1, 10000 do
    result = result .. "piece" .. i
end

-- Fast: table buffer + table.concat (O(n))
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece" .. i
end
local result = table.concat(parts)
```

Reason: Repeated `..` creates a new string each time, copying all prior content (quadratic time). `table.concat` allocates once and copies each piece exactly once (linear time).


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

Reason: `surface.DrawRect` bypasses the rounded-box logic entirely, avoiding the radius check and corner-drawing overhead that `draw.RoundedBox(0, ...)` still incurs.


```lua
-- Fastest: surface.DrawText with pre-set font/pos
surface.SetFont("DermaDefault")
surface.SetTextPos(x, y)
surface.SetTextColor(255, 255, 255, 255)
surface.DrawText("Your string here")
```

Reason: `surface.DrawText` avoids the internal overhead of `draw.SimpleText*` (which re-calculates text size, handles alignment, and creates temporary tables every call). Pre-setting font/position/color once per frame minimizes state changes.


```lua
local length = #myTable
```
Reason: In Lua (including Garry's Mod), the `#` operator returns the length of a sequence (array-like table with consecutive integer keys starting from 1). It's the standard and preferred way to get array length.


```lua
table.Empty(t)
```

Reason: `table.Empty(t)` clears the table in-place without allocating a new table object, avoiding GC pressure from the old table. `t = {}` creates a new table and leaves the old one for garbage collection.


```lua
-- Slow: O(n) linear search
local list = { "a", "b", "c", "d", "e" }
if table.HasValue(list, "c") then ... end

-- Fast: O(1) hash lookup
local set = { a = true, b = true, c = true, d = true, e = true }
if set["c"] then ... end
```

Reason: table.HasValue iterates the entire array each call; a hash-set key lookup is constant-time.


```lua
-- Faster: table constructor with known fields
local t = { field1 = "value1", field2 = "value2", field3 = "value3" }

-- Slower: assign fields after empty table
local t = {}
t.field1 = "value1"
t.field2 = "value2"
t.field3 = "value3"
```

Reason: Table constructors pre-allocate the hash table with the exact capacity needed, avoiding multiple rehash operations and separate key-value insertions that occur when assigning fields individually after creation.


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

Reason: `table.Random` iterates to count elements and handles non-sequential tables; for sequential tables, `math.random(1, #tbl)` directly indexes in O(1) with no iteration overhead.


```lua
x * x
```

Reason: Multiplication (`x * x`) is a single VM opcode and avoids the function call overhead of `math.pow` or the exponentiation operator `^` which dispatches to metamethods.


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

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

Reason: `player.GetAll()` returns a sequential array, so `ipairs` is more efficient than `pairs` and avoids the deprecated `k, v` pattern; `_` discards the unused index.


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

Reason: `ents.Iterator()` returns a stateless iterator that yields entities one at a time without allocating a table, unlike `ents.GetAll()` or `ents.FindByClass()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```
Reason: The `hook.Add` function registers a callback for the "Think" hook with the unique identifier "MyAddon.Think", which runs every frame on the server and client.


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

Reason: `IsValid(ent)` is the standard Garry's Mod way to verify an entity exists and hasn't been removed; it returns false for NULL entities, removed entities, and nil.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here
    local data = net.ReadTable() -- or other net.Read* functions
end)
```

Reason: `net.Receive` is the standard Garry's Mod API for registering handlers for named net messages.


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

function GetZeroAngle()
    zeroAngle.p = 0
    zeroAngle.y = 0
    zeroAngle.r = 0
    return zeroAngle
end
```

Reason: Reusing a single Angle instance and mutating its components avoids garbage allocation from repeated `Angle()` constructor calls in hot paths.


```lua
local myaddon = {}
myaddon.config = { color = Color(255, 0, 0) }

-- Cache frequently read setting in a local
local cfg_color = myaddon.config.color

-- Read (fastest)
local c = cfg_color
```

Reason: Local variable access is ~3-5x faster than table lookups; caching nested table values in locals avoids repeated indexing overhead.


```lua
-- Preferred DarkRP API
local jobName = ply:getDarkRPVar("job")
-- Or for full job table
local jobTable = ply:getJobTable()
```

Reason: `getDarkRPVar` is DarkRP's dedicated accessor for player variables (synced via DarkRP's own networking), avoiding generic `GetNWString` overhead and ensuring compatibility with DarkRP's variable system.


```lua
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- vectors are within threshold distance
end
```

Reason: `DistToSqr` avoids the expensive square root operation by comparing squared distances, making threshold checks significantly faster than using `Distance`.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- process ent
end
```
Reason: `ents.GetAll()` returns a table of all entities, and `ipairs` iterates it efficiently in C-side LuaJIT without creating intermediate tables, matching the wiki-recommended pattern for full entity scans.


```lua
local ply = Entity(1) -- or whatever player reference
local radius = 500
local nearby = ents.FindInSphere(ply:GetPos(), radius)
```

Reason: `ents.FindInSphere` uses the engine's spatial partition (octree/BSP) for O(log n) broad-phase culling before precise distance checks, making it consistently faster than `FindInBox` for radial queries and far cheaper than `FindInPVS` which tests visibility, not distance.


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

Reason: `player.GetAll()` returns only player entities directly, avoiding the overhead of `ents.FindInSphere` scanning all entities and the subsequent filtering loop. Using `DistToSqr` avoids expensive square root operations.


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

Reason: In Lua, numeric `for` loops are optimized at the VM level for counting iterations, avoiding the extra condition check and increment overhead of `while` loops.


```lua
-- Faster: Single hook.Run with all players
local players = player.GetAll()
hook.Run("MyCustomTick", players)

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

Reason: hook.Run has per-call overhead (listener lookup, validation, pcall); one call with a table avoids N−1 extra trips through the hook system.


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

    local hp = ply:Health()

    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 50, color_white)
end)
```

Reason: Caching `ply:Health()` in a local variable avoids three redundant method calls and `LocalPlayer()` lookups per frame, reducing overhead in the render hook.


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

hook.Add("HUDPaint", "ExamplePaint", function()
    -- use white instead of Color(255,255,255)
    surface.SetDrawColor(white)
    -- draw logic here
end)
```

Reason: Creating a new Color object every frame allocates memory and triggers garbage collection; caching it once avoids per-frame allocation.


```lua
local sin = math.sin

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

Reason: Localizing `math.sin` to a local variable avoids the global table lookup (`math` then `sin`) on every iteration, reducing overhead in tight loops.


```lua
local LocalPlayer = LocalPlayer

hook.Add("Think", "Example", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end
    -- use ply
end)
```

Reason: Caching LocalPlayer in a local upvalue avoids the global lookup and function call overhead on every invocation.


```lua
function PlayersLookingAtEachOther(ply1, ply2, tolerance)
    tolerance = tolerance or 0.7 -- ~45 degrees
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local toTarget = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local toSource = (ply1:GetPos() - ply2:GetPos()):GetNormalized()
    return aim1:Dot(toTarget) > tolerance and aim2:Dot(toSource) > tolerance
end
```

Reason: Uses cheap dot products on normalized vectors instead of expensive angle calculations; dot > 0.7 means < 45° deviation.


```lua
SomeHelper(ply)
```

Reason: Function call avoids table lookup and implicit self argument; can be local for fastest access.


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

Reason: `MsgN` writes directly to the console without the formatting overhead of `print`, making it significantly faster in hot paths.


```lua
local t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -- large sequential array

-- Fastest: numeric for
for i = 1, #t do
    local v = t[i]
    -- use v
end

-- Slower: ipairs
for i, v in ipairs(t) do
    -- use v
end

-- Slowest: pairs
for k, v in pairs(t) do
    -- use v
end
```

Reason: Numeric `for i = 1, #t` avoids iterator function overhead and key type checks; `ipairs` adds a C-function call per iteration; `pairs` iterates all keys including non-sequence ones and uses `next` with table traversal overhead.


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

-- Usage: fastFilterMap(players, function(p) return p:Alive() end, function(p) return p:Nick() end)
```

Reason: Avoids fn's closure allocations and multiple table passes; single loop with pre-allocated output table minimizes GC pressure and function call overhead.


```lua
local cachedPlayers = {}
local playerCount = 0

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

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

hook.Add("Think", "PlayerCache_ExampleUsage", function()
	for i = 1, playerCount do
		local ply = cachedPlayers[i]
		-- work with ply
	end
end)
```

Reason: Caches the player array once and only rebuilds it on join/leave events, eliminating the per-tick allocation and iteration overhead of `player.GetAll()`.


```lua
local playerData = {}

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

local function GetPlayerData(ply, key)
    return playerData[ply:SteamID64()] and playerData[ply:SteamID64()][key]
end

hook.Add("PlayerDisconnected", "CleanupPlayerData", function(ply)
    playerData[ply:SteamID64()] = nil
end)
```

Reason: Avoids NWVar networking overhead and metatable lookups; direct table access by SteamID64 is O(1) with zero serialization cost for server-side-only data.


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

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

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

Reason: Sequential arrays use contiguous memory and integer keys, enabling LuaJIT's fast-path optimization (`ipairs`/`#`), while string-keyed maps require hash lookups and scattered memory access.


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

Reason: Passing separate numbers avoids Color object allocation and table indexing overhead in the hot path.


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

Reason: Local SQLite runs in-process with zero network round-trips, while remote MySQL adds TCP latency, auth handshake, and connection pooling overhead for every query.


```lua
local steamIDCache = {}

local function GetCachedSteamID(ply)
    if not IsValid(ply) then return "" end

    local sid = ply:SteamID64()
    local cached = steamIDCache[sid]
    if cached then return cached end

    local steamid = ply:SteamID()
    steamIDCache[sid] = steamid
    return steamid
end

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    if IsValid(ply) then
        steamIDCache[ply:SteamID64()] = nil
    end
end)
```

Reason: Caches SteamID by SteamID64 (stable unique key) with automatic cleanup on disconnect, avoiding repeated C++ boundary calls on the hot path.


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

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

Reason: Repeated `..` creates a new string allocation on each iteration, copying all previous content. `table.concat` allocates once and copies each piece exactly once.


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

Reason: `surface.DrawRect` bypasses the `draw` library's overhead (argument validation, color handling, rounded-box logic) and maps directly to the engine's immediate-mode rectangle primitive.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Hello, World!")
```

Reason: `surface.DrawText` is the lowest-level text drawing function, avoiding the overhead of `draw.*` wrappers which perform font validation, color table handling, and position calculations each call. For single-line strings drawn every frame, direct surface calls are measurably faster.


```lua
local length = #myTable
```
Reason: In Garry's Mod Lua (and standard Lua 5.1+), the `#` operator is the idiomatic way to get the length of a sequential table (array-like with consecutive integer keys starting at 1). It's a built-in operator, not a function call, making it both preferred and performant.


```lua
table.Empty(t)
```

Reason: `table.Empty(t)` clears the table in-place without allocating a new table, avoiding GC pressure and reusing the existing array allocation. `t = {}` creates a new table, leaving the old one for garbage collection.


```lua
-- Slow: linear search O(n)
local list = { "a", "b", "c", "d", "e" }
local function hasValueSlow(tbl, val)
    return table.HasValue(tbl, val)
end

-- Fast: hash lookup O(1)
local set = { a = true, b = true, c = true, d = true, e = true }
local function hasValueFast(tbl, val)
    return tbl[val] ~= nil
end

-- Usage
print(hasValueSlow(list, "c"))  -- true
print(hasValueFast(set, "c"))   -- true
```

Reason: `table.HasValue` iterates the entire list (O(n)), while a hash-set lookup `tbl[val] ~= nil` is O(1) constant time.


```lua
local t = { field1 = "value1", field2 = "value2", field3 = "value3" }
```

Reason: Table constructors with known fields allocate the exact size needed in one operation, avoiding hash table resizing and multiple assignments.


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

Reason: `table.Random` iterates the table to count elements before selecting, while sequential tables have a known length via `#tbl`, allowing direct O(1) index access with `math.random(1, #tbl)`.


```lua
local x = 5
local squared = x * x
```

Reason: Multiplication (`x * x`) is faster than `x ^ 2` or `math.pow(x, 2)` because it avoids function call overhead and the exponentiation operator's extra branching. In tight loops, assign to a local variable first to avoid global lookups.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- ply is a Player entity
end
```
Reason: `player.GetAll()` returns a sequential array, so `ipairs` is faster and clearer than `pairs`; `_` discards the unused index.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process entity here
end
```

Reason: `FindByClass` directly retrieves only prop_physics entities without fetching all map entities first, making it the most efficient approach.


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

Reason: To register a callback function for Garry's Mod's Think hook using the MyAddon identifier


```lua
if ent and ent:IsValid() then
    -- Use ent safely here
end
```
Reason: Entities can become invalid after being removed/despawned, so we must check IsValid() before use.


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

Reason: This uses Garry's Mod's `net.Receive` system to register a handler for the "MyAddon.Sync" net message.


```lua
-- Method 1: Creating new Angle() each time (slower)
local function slow_method()
    return Angle(math.random(0, 360), math.random(0, 360), 0)
end

-- Method 2: Reusing a pre-allocated Angle reference (faster)
local fast_angle = Angle()
local function fast_method()
    fast_angle.pitch = math.random(0, 360)
    fast_angle.yaw = math.random(0, 360)
    fast_angle.roll = 0
    return fast_angle
end

-- Method 3: Method that zeroes an existing Angle (fastest)
local function zero_and_set(angle, pitch, yaw)
    angle:Zero()
    angle.pitch = pitch
    angle.yaw = yaw
    return angle
end

-- Benchmark setup
local trials = 100000
local start = os.clock()

for i = 1, trials do
    slow_method()
end

local slow_time = os.clock() - start

start = os.clock()

for i = 1, trials do
    fast_method()
end

local fast_time = os.clock() - start

print(string.format("Slow method: %f seconds", slow_time))
print(string.format("Fast method: %f seconds", fast_time))
print(string.format("Speedup: %fx", slow_time / fast_time))
```

Reason: Reusing Angle references avoids memory allocation overhead per call.


```lua
-- Preferred: Flat local variable
local color = myaddon.config_color

-- Nested table version (slower)
-- local color = myaddon.config.color
```

Reason: Local variables have faster access time than table lookups, especially for frequently read values.


```lua
local jobName = ply:GetCharacter():GetJob().Name
```

Reason: `ply:GetCharacter():GetJob().Name` is preferred in DarkRP as it accesses the job directly from the properly managed Character table, supporting job upgrades and other DarkRP job features, whereas `GetNWString("job")` stores basic job info only.


```lua
local function IsWithinDistance(vec1, vec2, threshold)
    return vec1:DistToSqr(vec2) < (threshold * threshold)
end
```

Reason: Using squared distance comparison avoids expensive sqrt calculation while giving identical threshold results.


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

```lua
for ent in ents.Iterator() do
    -- This loop visits every entity efficiently
end
```

Reason: The `ents.Iterator()` function is Garry's Mod wiki-recommended for maximum efficiency when iterating through all entities.```lua
for ent in ents.Iterator() do
    -- This loop visits every entity efficiently
end
```

Reason: The `ents.Iterator()` function is Garry's Mod wiki-recommended for maximum efficiency when iterating through all entities.


```lua
local player = Entity(1)
local position = player:GetPos()
local radius = 500
local entities = player:FindInSphere(position, radius)
```

Reason: FindInSphere is consistently faster than other spatial methods in Garry's Mod benchmarks and provides efficient radius-based queries for player-nearby entities.


```lua
local function GetPlayersInRadiusFast(pos, radius, filterHumans)
    local players = filterHumans and player.GetHumans() or player.GetAll()
    local result = {}
    local radiusSq = radius * radius

    for _, ply in ipairs(players) do
        if ply:GetPos():DistToSqr(pos) <= radiusSq then
            table.insert(result, ply)
        end
    end

    return result
end
```

Reason: The original approach using `ents.FindInSphere` retrieves all entities within the radius, requiring a filter operation to separate players from NPCs, props, and other entities. This wastes cycles finding and discarding non-player entities. The optimized version directly iterates through players using dedicated Garry's Mod player API functions (`player.GetAll()` or `player.GetHumans()`) and performs squared distance calculations to avoid `Sqrt()` calls, then checks if players are within radius. This reduces entity discovery overhead and processing for non-player objects, resulting in significant performance gains with many players online.


```lua
for i = 1, n do
    -- Your code here
end
```

Reason: for loops have better bytecode optimization and are compiled more efficiently in Lua interpreters.


```lua
-- Pattern 1: Efficient - Single hook call with all players
hook.Run("MyPlayerLogic", {player1, player2, player3})

-- Pattern 2: Inefficient - Multiple hook calls in a loop
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyPlayerLogic", ply)
end
```

Reason: Single hook call with player table avoids repeated hook system overhead