```lua
local lp = LocalPlayer()

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

hook.Add("PlayerSpawn", "cache_lp", function(ply)
    if ply == lp then lp = ply end
end)

-- use `lp` directly in think hooks, HUD draws, etc.
```

Reason: LocalPlayer() does a table scan of the player list each call; caching it in a local and refreshing only on spawn/InitPostEntity removes that per-frame lookup cost.


```lua
local function lookingAtEachOther(a, b, threshold)
    threshold = threshold or 0.5
    local toB = (b:GetPos() - a:GetPos()):GetNormalized()
    local toA = (a:GetPos() - b:GetPos()):GetNormalized()
    return a:GetAimVector():Dot(toB) > threshold
       and b:GetAimVector():Dot(toA) > threshold
end
```

Reason: the dot product of each player's normalized aim vector with the direction to the other measures facing directly, avoiding the trig cost of math.acos/angle-between.


```lua
SomeHelper(ply)
```

Reason: `ply:SomeHelper()` does a metatable `__index` lookup to resolve the method on every call, while a plain `SomeHelper(ply)` over a local reference skips that table lookup, so the direct function call is generally faster.


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

Reason: MsgN skips print's per-argument type dispatch and formatting overhead, writing raw strings straight to the console.


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

Reason: Numeric for avoids per-iteration function calls and hash lookups, running in pure array-index speed, whereas ipairs adds iterator overhead and pairs is slowest due to scanning the whole hash part.


```lua
-- Plain imperative transforms: one pass, no closures, no table churn.
-- Faster than DarkRP's fn library, which allocates a new wrapped table
-- and constructs closures per operation on every chain step.

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

-- Example: keep even numbers, square them.
local src = {1, 2, 3, 4, 5, 6}
local res = filterMap(src,
    function(x) return x % 2 == 0 end,
    function(x) return x * x end
)
-- res == {4, 16, 36}
```

Reason: A single fused pass with a pre-sized output array avoids fn's per-step table allocation and closure construction, giving better cache locality and no combinator overhead.


```lua
local CachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "CachePlayers", RefreshPlayers)
hook.Add("PlayerDisconnected", "CachePlayers", RefreshPlayers)
hook.Add("InitPostEntity", "CachePlayers", RefreshPlayers)

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        -- per-tick work here, no player.GetAll() call
    end
end)
```

Reason: Iterating a cached numeric array with a numeric `for` avoids both the `player.GetAll()` allocation and `ipairs` overhead on every tick, rebuilding the table only on join/leave events.


```lua
local PlayerCache = {}
local entGetID = FindMetaTable("Player").EntIndex

-- write
PlayerCache[entGetID(ply)] = value

-- read (hot path)
local v = PlayerCache[entGetID(ply)]
```
Reason: Reads hit a plain local table via an integer key instead of traversing the Player metatable's `__index`, avoiding per-access metamethod overhead.


```lua
local seq = {"a", "b", "c", "d"}
for i = 1, #seq do
    local v = seq[i]
end
```
Reason: Sequential number-indexed arrays iterate via a numeric `for i = 1, #t` loop with direct O(1) integer slot access in the array part, avoiding the hash lookups and `next()` overhead that string-keyed maps require under `pairs`.


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

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


```lua
-- Local SQLite via the built-in sql library (synchronous, in-process)
local escaped = sql.SQLStr( ply:SteamID64() )
local row = sql.QueryRow( "SELECT money FROM players WHERE steamid = " .. escaped .. " LIMIT 1" )
local money = row and tonumber( row.money ) or 0
```
Reason: SQLite runs in-process on the local disk with no network round-trip, so reads/writes are typically lower latency than remote MySQL, whose queries cross the network to another host.


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

local plyMeta = FindMetaTable("Player")
local _SteamID = plyMeta.SteamID

function plyMeta:SteamID()
    local cached = steamIDCache[self]
    if cached ~= nil then return cached end
    local id = _SteamID(self)
    steamIDCache[self] = id
    return id
end

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

Reason: SteamID() recomputes from the net channel each call; caching on the player (weak-keyed so disconnected players are GC'd) returns the stored string on repeat calls, dropping per-call cost to a table lookup.


Answer must contain 0 through 0 candidate loops.

```lua
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece_" .. i
end
local result = table.concat(parts)
```
Reason: Repeated `..` reallocates and copies a growing string each iteration (O(n²)); collecting pieces in a table and calling `table.concat` once builds the result in a single pass (O(n)).


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

Reason: `draw.RoundedBox(0, ...)` still runs the rounded-rect path (radius clamping, corner math, poly building); `surface.DrawRect` is a single flat quad with no rounding logic, so it's the minimal draw call for axis-aligned rectangular fills.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 10)
surface.DrawText("Hello every frame")
```

Reason: For a single line, the raw surface.* sequence avoids the multiline/wrapping and argument-handling overhead in draw.DrawText and draw.SimpleTextOutlined, making it the fastest per-frame path.


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

Reason: The `#` length operator is the preferred, O(1) way to get the length of a sequential array-like table; `table.Count` iterates all pairs and is meant for non-sequential tables.


```lua
local t = t or {}
t = {}
```

Reason: `t = {}` allocates one new table (O(1)) and lets the old one be GC'd, whereas `table.Empty(t)` walks every key to set it to nil (O(n)), so for a large table the reassign is generally faster.


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

Reason: A hash lookup is O(1) versus table.HasValue's O(n) linear scan over the list.


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

Reason: A single constructor pre-sizes the hash part and inserts all keys at once, avoiding the repeated rehash/lookup overhead of separate `t.a = ...` assignments after `{}`.


```lua
local t = {"a", "b", "c", "d", "e"}

local elem = t[math.random(#t)]
```
Reason: `table.Random` internally builds a key list and iterates the table each call, whereas `t[math.random(#t)]` uses the sequential table's length directly for a single O(1) index lookup.


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

Reason: `x * x` avoids the `math.pow` call that `x^2` compiles to, so it is faster in a tight loop.


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

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

Reason: `player.Iterator()` is the modern Garry's Mod API that lazily yields each connected player without allocating a table, replacing the older `pairs(player.GetAll())` pattern.


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

Reason: `ents.Iterator()` is a coroutine-based generator that yields every entity one at a time, so no intermediate table is built.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- optional callback body
end)
```
Reason: The `hook.Add` function registers a callback for a specified hook with a unique identifier, ensuring the callback runs each frame when the Think hook fires.


Uses IsValid for entity/object validity.

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

Reason: `IsValid(ent)` returns `true` only when `ent` references a non-removed, non-stale entity; if the entity was removed or garbage-collected, the function returns `false`, preventing attempts to index nil and breaking the script.


```lua
net.Receive("MyAddon.Sync", function(len)
    local data = net.ReadString() -- example: adapt to your protocol
    -- handle the incoming data here
end)
```

Reason: Registers a callback for the "MyAddon.Sync" message so it fires when a client receives that message from the server.


```lua
-- Reusable zeroed Angle pool (hot path)
local ZeroAngles = Angle(0, 0, 0)

function ResetAngle(a)
    a.p = 0
    a.y = 0
    a.r = 0
    return a
end

-- Usage in a hot loop
local ang = Angle() -- allocate once if you need a fresh one
for i = 1, 10000 do
    ResetAngle(ang)  -- re-zero in place
    -- use ang ...
end
```

Reason: Reusing and zeroing a single Angle table avoids repeated table allocation and garbage collection pressure in tight loops.


```lua
local color = myaddon.config.color
local r, g, b = color[1], color[2], color[3]
```

Reason: Flat locals avoid repeated table-index chains; Lua resolves the path each time, so caching into a local eliminates two extra field lookups per read.


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

Reason: `getDarkRPVar` is DarkRP's official accessor — it reads from DarkRP's managed networked variable system and respects any internal caching or update logic, whereas `GetNWString("job")` bypasses DarkRP's abstraction layer and can break if the internal key changes.


```lua
local a = Vector(100, 200, 300)
local b = Vector(400, 500, 600)
local threshold = 1000

if a:DistToSqr(b) < threshold * threshold then
    print("Close enough")
end
```

Reason: `DistToSqr` avoids the expensive square root inside `Dist`, so for threshold checks you square the threshold instead and compare squared distances.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- visit ent
end
```
Reason: `ents.GetAll()` returns a table of all entities and is the standard, clear way to iterate; the wiki-recommended `ipairs` over this table avoids repeated C↔Lua calls and is efficient for most use cases.


```lua
local nearby = ents.FindInSphere( ply:GetPos(), 512 )
```
Reason: `ents.FindInSphere` is consistently the fastest built-in spatial query in GMod benchmarks — O(n) with a distance check rather than the heavier visibility or PVS overhead.


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

Reason: `player.GetAll()` returns a cached, tiny table (~100 entries max) so you skip the world-entities scan entirely; combining it with LengthSqr avoids the sqrt inside the radius check.


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

Reason: In Garry's Mod Lua (GLua), `while` avoids the per-iteration overhead of `for`'s range iteration internals (table lookups for limit/step and the compare-and-assign logic), making a hand-rolled `while` counter marginally faster for simple counts.


```lua
-- SLOWER: hook.Run lookup repeated every player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyTick", ply)
end

-- FASTER: single hook.Run call, single lookup
hook.Run("MyTick", player.GetAll())
```

Reason: `hook.Run` performs a table lookup and iteration over registered hooks internally; calling it once avoids repeating that overhead per player.


```lua
hook.Add("HUDPaint", "OptimizedHealthHUD", function()
    local hp = LocalPlayer():Health()
    -- Use hp three times below instead of calling :Health() each time
    surface.SetDrawColor(255, 0, 0)
    surface.DrawRect(10, 10, hp, 20)
    draw.SimpleText(hp, "Default", 10, 40, color_white)
    draw.RoundedBox(4, 10, 60, hp, 20, Color(255, 0, 0))
end)
```

Reason: Caching `LocalPlayer():Health()` in a local eliminates two redundant method calls per frame, reducing overhead from `LocalPlayer` table lookups and the `Health` method invocation.


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

function PANEL:Paint(w, h)
    draw.RoundedBox(4, 0, 0, w, h, WHITE)
end
```

Reason: Hoisting the `Color()` call to module scope avoids allocating a new userdata every frame.


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

Reason: Caching `math.sin` in a local eliminates repeated global-table lookups each iteration, and locals resolve to direct stack-index operations in LuaJIT, which powers Garry's Mod.


```lua
local ply
hook.Add("Think", "CacheLocalPlayer", function()
    ply = LocalPlayer()
end)
```
Reason: Caching LocalPlayer() once per frame in a shared local eliminates repeated engine lookups while always reflecting the current player object.


```lua
function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.5
    local pos1 = ply1:GetPos()
    local pos2 = ply2:GetPos()
    local dir12 = (pos2 - pos1):GetNormalized()
    local dir21 = -dir12
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    return aim1:Dot(dir12) > threshold and aim2:Dot(dir21) > threshold
end
```

Reason: Using dot products of aim vectors with direction vectors avoids costly trigonometric functions while still providing a configurable rough check.


```lua
-- preferred: direct function call
local function SomeHelper(ply)
  -- ...
end

SomeHelper(ply)
```

Reason: Method calls incur an extra table lookup and must resolve `self` at runtime; a direct call skips both overheads.


```lua
-- print is a Lua wrapper: converts all args, joins with tabs, then calls Msg
-- MsgN is the direct C binding — fewer allocations, no tab-join pass
MsgN("debug: ", variable)
```

Reason: `MsgN` is the native C function that `print` wraps; skipping the intermediate Lua argument conversion and tab-join allocation makes it faster in hot loops.


```lua
local t = {1, 2, 3, ..., N} -- large sequential array
local sum = 0
for i = 1, #t do
    sum = sum + t[i]
end
```
Reason: Numeric for loops avoid iterator overhead and are optimized in LuaJIT/GMod, making them fastest for sequential numeric arrays.


```lua
-- Slower: DarkRP fn combinators (allocates closures + intermediate tables)
local result = fn.filter(function(v) return v.active end, players)
result = fn.map(function(v) return v:Name() end, result)
result = fn.sortBy(function(v) return v:Name() end, result)

-- Faster: plain numeric for loop, single pass, no intermediates
local out = {}
for i = 1, #players do
  local p = players[i]
  if p.active then
    out[#out + 1] = p:Name()
  end
end
table.sort(out)
```

Reason: Direct loops avoid per-element closure dispatch, table reconstruction, and virtual-call overhead that DarkRP's `fn` combinators pay on every element — LuaJIT also hoists numeric `for` invariants and elides bounds checks the closure variant cannot.


```lua
-- Cache for player list, refreshed only on join/leave events
local cachedPlayers = {}
local function RefreshPlayerCache()
    cachedPlayers = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "UpdateCachedPlayers", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "UpdateCachedPlayers", RefreshCache)
-- Initialize cache at load (handles players already connected)
RefreshCache()

-- Example Think hook using cache (no per-tick GetAll)
hook.Add("Think", "MyOptimizedHook", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Your per-tick logic here
    end
end)
```
Reason: Caching avoids per-tick player table rebuilds; events update cache only when necessary, reducing allocations and CPU overhead.


```lua
local PLAYER_DATA = {}

hook.Add("PlayerInitialSpawn", "init_data", function(ply)
    PLAYER_DATA[ply] = { someField = 0 }
end)

hook.Add("PlayerDisconnected", "cleanup_data", function(ply)
    PLAYER_DATA[ply] = nil
end)

-- Read: upvalue lookup beats Entity metatable access
local function GetSomeField(ply)
    return PLAYER_DATA[ply].someField
end

-- Write
local function SetSomeField(ply, val)
    PLAYER_DATA[ply].someField = val
end
```

Reason: Table keyed by entity reference with upvalue local avoids repeated `ply` metatable lookups and `__index` calls that `ply.someField` incurs through `Entity`'s C++ accessor chain.


```lua
-- Sequential array (integer-indexed from 1..N)
local items = { "alpha", "bravo", "charlie", "delta", "echo" }

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

Reason: LuaJIT (and stock Lua) stores sequential integer-indexed arrays as dense, contiguous memory with O(1) index lookup; string-keyed maps are hash tables with hash-compute + collision handling overhead, making array iteration faster for both single and bulk traversal.


```lua
-- Fast: primitive arguments passed directly to C
surface.SetDrawColor(255, 0, 0)
```

Reason: Passing separate r,g,b numbers avoids constructing a Color table and its field lookups, sending primitives directly to the C function.


```lua
-- Create a table if it doesn't exist
sql.Query([[CREATE TABLE IF NOT EXISTS player_data (
    steam_id TEXT PRIMARY KEY,
    name TEXT,
    score INTEGER
)]])

-- Insert a record
sql.Query([[INSERT OR REPLACE INTO player_data (steam_id, name, score) VALUES ('STEAM_0:1:123456', 'PlayerName', 100)]])

-- Retrieve a record
local result = sql.QueryValue([[SELECT score FROM player_data WHERE steam_id = 'STEAM_0:1:123456']])
print("Score:", result)
```
Reason: SQLite runs in‑process, avoiding network latency and the overhead of a MySQL client/server round‑trip.


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

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

Reason: Weak-key table avoids hard-referencing players, and lookup replaces repeated SteamIDString method calls.


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

Reason: `table.concat` builds the final string in one allocation pass, while repeated `..` creates and discards a new intermediate string on every join, giving O(n²) time and memory churn.


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

Reason: `DrawRect` skips the radius branch and rounding logic that `RoundedBox(0, …)` still evaluates, making it a single native call instead of a Lua function wrapping one.


```lua
surface.SetFont("DermaLarge") -- choose a font once
surface.SetTextPos(100, 100)   -- set position
surface.DrawText("Hello")      -- draw the string
```
Reason: Directly using the low‑level `surface.*` calls avoids the extra outline pass and wrapper overhead of `draw.DrawText` or `SimpleTextOutlined`, giving the fastest per‑frame drawing.


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

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


```lua
-- Faster: reuse the existing table in-place
table.Empty(t)
-- Slower: creates a new table; old one awaits GC
t = {}
```
Reason: `table.Empty(t)` is O(n) but avoids allocation and GC pressure; `t = {}` is O(1) to assign but the abandoned table triggers a future GC sweep whose aggregate cost on large tables exceeds the one-shot clear.


```lua
local list = {"apple", "banana", "cherry"}

-- Slow: O(n) linear scan per lookup
for _, v in ipairs(list) do
  if v == "banana" then print("found") end
end

-- Fast: O(1) average-case set lookup
local set = {}
for _, v in ipairs(list) do set[v] = true end

if set["banana"] then print("found") end
```

Reason: `table.HasValue` and `ipairs` loops are O(n) per check; converting the list to a hash-set lets you test membership with a single O(1) key lookup.


```lua
-- Table constructor (faster for known, small tables)
local a = { x = 1, y = 2, z = 3 }

-- Field-by-field assignment (slower: extra opcodes per SETTABLE)
local b = {}
b.x = 1
b.y = 2
b.z = 3
```

Reason: The constructor compiles to a single SETLIST that sets N fields in one pass, while separate assignments emit N individual SETFIELD opcodes each with their own lookup overhead.


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

-- Usage:
local myTable = {"apple", "banana", "cherry"}
local chosen = randomElement(myTable)
```

Reason: `tbl[math.random(#tbl)]` is O(1) constant-time indexing, while `table.Random` is O(n) — it calls `table.GetKeys` to build an index array then shuffles it to pick one element.


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

Reason: Multiplication avoids function-call overhead that `math.pow` or `x^2` (operator precedence aside) would incur, making `x * x` the fastest form in tight Lua loops.


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

Reason: `player.Iterator()` is the recommended idiom in modern Garry's Mod Lua; it yields each connected player exactly once without allocating an intermediate table, unlike the older `player.GetAll()` + `pairs()` pattern.


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

Reason: `ents.Iterator()` returns a stateless iterator that yields entities on demand without constructing an intermediate table.


```lua
hook.Add( "Think", "MyAddon.Think", function()
    -- Your callback logic here
end )
```
Reason: `hook.Add` registers a callback on a named hook; the first argument is the hook name ("Think"), the second is the unique identifier ("MyAddon.Think"), and the third is the function to run.


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

Reason: `IsValid` returns `false` for NULL / removed entities in Garry's Mod; calling methods on them would error or crash.


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

Reason: This is a direct knowledge question about Garry's Mod Lua API, not a coding task that requires tools.


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

-- hot path: zero it instead of constructing
a:Set(0, 0, 0)
```

Reason: `Angle()` allocates a new userdata every call; zeroing a reusable table avoids GC pressure.


```lua
local color = myaddon.config.color  -- flatten once at file scope
print(color.r, color.g, color.b)
```

Reason: Local variable access is a single register lookup; nested table access (`myaddon.config.color`) requires chained hash-table lookups, each adding hash-and-compare overhead that compounds on frequent reads.


```lua
-- Preferred: DarkRP's own accessor
local jobName = ply:getDarkRPVar("job")

-- Avoid: raw networked string
local jobName = ply:GetNWString("job")
```

Reason: `getDarkRPVar("job")` is DarkRP's dedicated accessor that reads from its internal variable table, staying in sync with job changes and respecting DarkRP's update cycle rather than bypassing it with raw networked variables.


```lua
if v1:DistToSqr(v2) < threshold * threshold then
    -- vectors are within range
end
```

Reason: `DistToSqr` avoids the expensive square root that `Distance` performs, and since you only need a threshold comparison, working with squared distances is both faster and equivalent.


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

Reason: `ents.GetAll()` is the wiki-recommended way to iterate all entities efficiently; it returns a pre-built table, avoiding the overhead and inconsistency of older patterns like `while` loops with entity enumeration.


```lua
local function GetNearbyEntities(pos, radius)
    return ents.FindInSphere(pos, radius)
end

local function GetPlayersNearby(ply, radius)
    return GetNearbyEntities(ply:GetPos(), radius)
end
```

Reason: `ents.FindInSphere` is a single C++ call with O(n) sphere check—faster than FindInBox for point queries, and avoids PVS overhead for dynamic radius searches.


```lua
function FindPlayersNear(pos, radius)
    local r2 = radius * radius
    local result = {}
    local px, py, pz = pos.x, pos.y, pos.z
    for _, p in ipairs(player.GetAll()) do
        local d = p:GetPos()
        local dx, dy, dz = d.x - px, d.y - py, d.z - pz
        if dx*dx + dy*dy + dz*dz <= r2 then
            result[#result + 1] = p
        end
    end
    return result
end
```

Reason: `ents.FindInSphere` iterates all entities then filters, while `player.GetAll()` with manual distance checks is O(players) instead of O(entities) and avoids allocating an intermediate table of non-player entities.


```lua
local function count(n)
    local i = 1
    while i <= n do
        i = i + 1
    end
end
```

Reason: The numeric `for` loop is faster in Garry's Mod Lua because its bounds and increment are handled internally by the VM, avoiding repeated Lua-level comparisons and variable assignments each iteration.


```lua
-- Example: notifying custom logic for all players each tick
-- Fast pattern: single hook call with the player table
hook.Add("Think", "NotifyAllPlayers", function()
    local players = player.GetAll()
    hook.Run("NotifyPlayers", players)
end)

-- Inside the hook that handles the notification:
hook.Add("NotifyPlayers", "ProcessPlayers", function(players)
    for _, ply in ipairs(players) do
        -- custom logic for each player goes here
        -- e.g. ply:SendLua("...")
    end
end)
```
Reason: A single hook.Run call avoids repeated hook lookups per player, reducing overhead and improving tick performance.


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

draw.RoundedBox(6, 10, 10, hp * 2, 30, Color(255, 0, 0))
draw.RoundedBox(6, 10, 10, hp * 2, 30, Color(255, 255, 0))
draw.SimpleText(hp, "DermaLarge", 15, 15, Color(255, 255, 255))
```
Reason: Caches `LocalPlayer():Health()` once into a local instead of calling it three times, reducing three method lookups and engine calls to one.


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

Reason: Allocating a new Color table every frame creates garbage and GC pressure; hoisting the constant into an upvalue avoids repeated allocation.


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

Reason: Local variable lookup avoids repeated global table indexing of `math.sin` each iteration.


```lua
local ply = LocalPlayer()
-- Use `ply` directly; reassign after game reset / respawn if needed.
-- For example, hook once and cache:
hook.Add("InitPostEntity", "CacheLocalPlayer", function()
    ply = LocalPlayer()
end)
```

Reason: Caching the reference eliminates repeated engine lookups; `LocalPlayer()` is cheap but calling it every frame adds unnecessary overhead in hot loops.


```lua
local function AreLookingAtEachOther(ply1, ply2)
    local dir1 = ply1:GetAimVector()
    local dir2 = ply2:GetAimVector()
    local toTarget = (ply2:GetPos() - ply1:GetPos()):GetNormalized()

    local dot1 = dir1:Dot(toTarget)
    local dot2 = dir2:Dot(-toTarget)

    return dot1 > 0.7 and dot2 > 0.7
end
```

Reason: Dot product of unit vectors gives the cosine of the angle directly; comparing against a threshold (0.7 ≈ ~45° cone) is cheaper than `math.acos` and avoids trig entirely.


```lua
-- Method syntax: ply:SomeHelper()
-- Function syntax: SomeHelper(ply)
-- Both compile to identical bytecode
```

Reason: Equivalent; `:` is syntactic sugar for `.method(self, args)`.


```lua
MsgN("[DEBUG] " .. tostring(value))
```

Reason: `MsgN` writes directly to the console without the overhead of `print`'s format parsing and is faster in hot paths.


Answer must contain 1 through 1 candidate loops.

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

-- ipairs: iterator-based, safest but slowest on huge tables
local s1 = SysTime()
local sum = 0
for _, v in ipairs(t) do sum = sum + v end
print("ipairs: " .. tostring(SysTime() - s1))

-- pairs: hash-map iterator, even slower; unordered
local s2 = SysTime()
sum = 0
for _, v in pairs(t) do sum = sum + v end
print("pairs:  " .. tostring(SysTime() - s2))

-- numeric for: fastest — direct index math, no iterator overhead
local s3 = SysTime()
sum = 0
for i = 1, #t do sum = sum + t[i] end
print("for i:  " .. tostring(SysTime() - s3))
```

Reason: numeric `for` with `#t` is fastest because it avoids iterator-closure allocation and per-iteration function calls, operating directly on array indices and memory offsets.


```lua
-- Instead of: fn.Map(fn.Filter(items, predicate), transform)
-- Use plain loops:

local function process(items, predicate, transform)
  local out = {}
  for i = 1, #items do
    local v = items[i]
    if predicate(v) then
      out[#out + 1] = transform(v)
    end
  end
  return out
end
```

Reason: Eliminates closure allocation and per-element function-call overhead that `fn` combinators incur; plain `for` loops are the fastest iteration primitive in LuaJIT/GMod.


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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCache", function(ply)
    cachedPlayers = player.GetAll()
    lastPlayerCount = #cachedPlayers
end)

hook.Add("PlayerDisconnected", "UpdatePlayerCache", function(ply)
    timer.Simple(0, function()
        cachedPlayers = player.GetAll()
        lastPlayerCount = #cachedPlayers
    end)
end)

hook.Add("Think", "UsePlayerCache", function()
    if #cachedPlayers ~= player.GetCount() then
        cachedPlayers = player.GetAll()
    end
    for _, ply in ipairs(cachedPlayers) do
        -- your per-tick logic here
    end
end)
```

Reason: Uses PlayerInitialSpawn and PlayerDisconnected hooks to rebuild the cache only on player count changes, with a cheap `player.GetCount()` comparison as a safety net in Think, avoiding a full `player.GetAll()` allocation every tick.


```lua
local playerData = {}

-- Write
playerData[ply:UserID()] = value

-- Read
local v = playerData[ply:UserID()]
```

Reason: Direct table indexing with an integer key avoids the entity metatable lookup chain that `ply.someField` triggers, giving you a single hash-table access instead of a VTable traversal plus string comparison.


```lua
-- Faster: sequential number-indexed array
local data = { 1, 2, 3, 4, 5 }

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

Reason: Arrays use a dense integer-partitioned hash table allowing direct index lookup and predictable linear memory access, while string-keyed maps trigger full hash lookups per key and scatter values in memory, defeating cache locality.


```lua
surface.SetDrawColor(r, g, b) -- faster: avoids Color object allocation and table lookup
```
Reason: The numeric form skips constructing and passing a Color table object, going straight to the native C call with plain numbers.


```lua
local result = sql.Query("SELECT * FROM players WHERE steamid = " .. sql.SQLStr(steamid) .. " LIMIT 1")
if result then
    return result[1]
end
```

Reason: SQLite runs in-process with zero network latency, making it faster than remote MySQL for single-server read/write workloads.


```lua
-- Per-player SteamID cache using Entity index as key
local steamIdCache = setmetatable({}, { __mode = "k" }) -- weak keys so entities can be GC'd

local function GetSteamID(ply)
    local id = steamIdCache[ply]
    if id then return id end
    id = ply:SteamID()
    steamIdCache[ply] = id
    return id
end
```

Reason: Table lookup avoids the string allocation + network query inside SteamID(); weak keys prevent leaked entity references from blocking GC.


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

Reason: `table.concat` builds the final string in a single allocation pass, while repeated `..` creates a new temporary string on every append, leading to O(n²) memory copying.


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

Reason: `draw.RoundedBox` validates and clamps the corner-radius parameter before deciding whether to call the rounded-path helper or fall through to a plain rect; `surface.DrawRect` skips all of that bookkeeping and issues a single unclipped quad draw directly to the material system, shaving the Lua-side overhead on every call.


```lua
-- Cache everything outside the hook, then use raw surface calls
local font = "DermaLarge"
local color = Color(255, 255, 255, 255)
local x, y = 100, 100

hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(font)
    surface.SetTextColor(color)
    surface.SetTextPos(x, y)
    surface.DrawText("Hello, world!")
end)
```

Reason: `surface.DrawText` is a single low-level call with no wrapping, outline, or shadow overhead—`draw.SimpleTextOutlined` makes 5+ surface calls (shadow + outline + fill) and `draw.DrawText` adds per-frame word-wrap computation.


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

Reason: The `#` operator is the standard, idiomatic way to get the length of a sequential (list-like) table in Lua.


```lua
-- Slower: iterates every key, sets each to nil
table.Empty(t)

-- Faster: replaces reference, old table becomes garbage
t = {}
```

Reason: `table.Empty(t)` walks every key and sets it to nil (O(n) with per-key overhead), while `t = {}` is a single pointer swap (O(1)) and lets the GC collect the old table — the GC pause cost is amortized and far cheaper than n individual deletions when n is large.


```lua
local set = { [1] = true, [2] = true, [3] = true }

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

Reason: Indexed lookup is O(1) while table.HasValue linearly scans the list.


```lua
-- Slower: assign after creation
local t = {}
t.name = "Alice"
t.age = 30

-- Faster: constructor
local t = { name = "Alice", age = 30 }
```

Reason: The constructor form performs one allocation and sets all keys in a single step, avoiding repeated hash-table insertions and extra lookups each `t.key = val` line triggers.


```lua
local el = t[math.random(#t)]
```

Reason: `table.Random` iterates the table's keys to collect valid entries, while `math.random(#t)` + direct array index avoids the iteration and function-call overhead for sequential (contiguous 1–n) tables.


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

Reason: Multiplication is faster than `math.pow(x, 2)` or `x^2` in Garry's Mod LuaJIT due to avoiding function call overhead and extra operator dispatch.


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

Reason: `player.Iterator()` avoids the intermediate table allocation that `player.GetAll()` creates, reducing garbage collection pressure — especially noticeable with high player counts.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process the entity here
    end
end
```
Reason: Using `ents.Iterator()` yields entities one-by-one from the C++ engine without constructing a Lua table of all entities, satisfying the constraint to avoid pre‑building a table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Think callback body
end)
```
Reason: Demonstrates the hook.Add syntax for registering a named callback on the Think hook with the specified identifier.


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

Reason: `IsValid()` returns `true` only when the entity hasn't been removed (isn't NULL); calling methods on an invalid entity throws a Lua error.


```lua
net.Receive("MyAddon.Sync", function(len)
    local someValue = net.ReadString()
    -- handle the message
end)
```

Reason: This uses Garry's Mod `net.Receive` to register a callback for incoming messages with the given name.


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

-- In hot path, reuse and zero fields instead of allocating:
local function getZeroAngle(out)
    out.p = 0
    out.y = 0
    out.r = 0
    return out
end
```

Reason: `Angle()` allocates new userdata every call; zeroing a pre-allocated Angle's fields avoids GC pressure and allocation cost in hot loops.


```lua
local cachedColor = myaddon.config.color  -- one-time lookup, then local
print(cachedColor)  -- fast local read
```

Reason: Local variables live in registers and are accessed in one instruction; nested table indexing requires multiple sequential hash lookups per read, so caching into a local eliminates the repeated traversal on hot paths.


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

Reason: `getDarkRPVar` is the DarkRP-specific abstraction over `GetNWString`, keeping your code consistent with DarkRP's internal variable system and future-proof against implementation changes.


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

Reason: `DistToSqr` avoids the costly `sqrt` that `Distance` performs, and comparing against a squared threshold is sufficient for range checks.


```lua
for _, ent in ents.Iterator() do
    -- your logic here
end
```
Reason: `ents.Iterator()` is the wiki-recommended, allocation-free iterator for visiting every entity in the engine's internal list.


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

Reason: FindInSphere is one of the faster built-in spatial queries because it uses a simple distance check against entity positions with early-out potential, making it efficient for radius-based proximity searches compared to other FindIn* methods.


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

Reason: `player.GetAll()` iterates only the player list (typically ~64 entries max) with a cheap squared-distance check, avoiding `ents.FindInSphere`'s broad-phase spatial query across thousands of world + NPC + prop entities followed by type filtering.


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

Reason: The `for` loop compiles to Lua's `FORLOOP` opcode which keeps the counter in a register and does increment+compare+branch in a single bytecode instruction, whereas `while` requires separate ADD, LT, and JMP instructions on a heap-allocated table value.


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

-- FASTER: 1 hook.Run call per tick
hook.Run("MyHook", player.GetAll())
```

Reason: `hook.Run` pays string-lookup, argument-pack, and call overhead on every invocation; one call with the player list avoids repeating that overhead N times.


```lua
hook.Add("HUDPaint", "DrawHealth", function()
    local hp = LocalPlayer():Health()
    surface.SetDrawColor(255, 0, 0)
    surface.DrawRect(10, 10, hp, 20)
    draw.SimpleText(hp, "DermaLarge", 15, 15, Color(255, 255, 255))
    draw.RoundedBox(6, 10, 40, hp * 0.5, 20, Color(200, 0, 0))
end)
```

Reason: Caching `LocalPlayer():Health()` in a local variable avoids three repeated method calls and entity lookups, eliminating redundant `GetNet`/replication traffic within the same frame.


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

-- Inside your paint function:
surface.SetDrawColor(white)
surface.DrawRect(0, 0, ScrW(), ScrH())
```

Reason: `Color()` allocates a new table every call; caching the color outside the loop avoids per-frame garbage collection pressure.


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

Reason: Hoisting `math.sin` into a local avoids repeated global table lookups on each iteration.


```lua
local ply
hook.Add("Think", "cacheLocalPlayer", function()
  ply = LocalPlayer()
end)
```
Reason: Caches the result in a local variable updated once per frame, so subsequent code reads `ply` (a fast table lookup) instead of calling `LocalPlayer()` repeatedly, which internally performs a full engine call each time.


```lua
function AreLookingAtEachOther(ply1, ply2)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local toOther1 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local toOther2 = (ply1:GetPos() - ply2:GetPos()):GetNormalized()
    return aim1:Dot(toOther1) > 0.5 and aim2:Dot(toOther2) > 0.5
end
```
Reason: Uses dot products of aim vectors with direction vectors to each other, avoiding acos and expensive angle calculations.


```lua
-- Preferred: local function + direct call
local function SomeHelper(ply)
    -- your logic
end

SomeHelper(ply)
```

Reason: `ply:SomeHelper()` desugars to a table index on the entity then a call, whereas a local function call is a single `GETTABL` + `CALL` avoiding the entity lookup overhead.


```lua
-- Hot-path debug: MsgC avoids print's format/prefix overhead
MsgC(Color(255, 255, 0), "[DBG] ", Color(200, 200, 200), tostring(x), "\n")
```
Reason: `MsgC` (or `Msg`) skips `print`'s implicit `tostring` + prefix assembly and goes straight to the engine's message buffer.


```lua
local t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for i = 1, #t do
  local v = t[i]
end
```

Reason: Numeric `for` avoids per-iteration function-call overhead (`pairs`/`ipairs` each invoke a C iterator and yield the key+value), uses direct integer indexing into the array part of the table, and keeps the loop body in pure Lua with no iterator state machine — making it the fastest for sequential numeric arrays.


```lua
-- fast-pipeline.lua
-- A minimal, allocation-free pipeline that beats DarkRP's fn library on hot paths.
-- Usage:
--   local result = pipeline(data, filterFn, mapFn, ...)

local function pipeline(list, ...)
  local n = select('#', ...)
  local out = list
  for i = 1, n do
    local op = select(i, ...)
    local next = {}
    local len = 0
    for j = 1, #out do
      local v = op(out[j], j)
      if v ~= false and v ~= nil then
        len = len + 1
        next[len] = v
      end
    end
    out = next
  end
  return out
end

-- Example: filter odds, square them
local nums = {1,2,3,4,5,6,7,8,9,10}
local result = pipeline(nums,
  function(x) return x % 2 == 1 end,   -- keep odds
  function(x) return x * x end          -- square
)
-- result == {1, 9, 25, 49, 81}
```

Reason: Single-pass loops with no closure allocation per step, no intermediate iterator objects, and no table lookups — just raw Lua for-loops which the LuaJIT/GMod server compiler can optimize far better than the generic higher-order wrappers in the fn library.


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

hook.Add("PlayerInitialSpawn", "PlayerCacheJoin", function(ply)
    table.insert(cachedPlayers, ply)
    cachedPlayerCount = #cachedPlayers
end)

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

-- Use cachedPlayers in your Think hook instead of player.GetAll()
hook.Add("Think", "PlayerCacheThink", function()
    for i = 1, cachedPlayerCount do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- your per-player logic here
        end
    end
end)
```

Reason: Caching avoids allocating a new table and iterating `player.GetAll()` every tick; the list is rebuilt only on join/leave, keeping the hot loop zero-allocation and bounded by the actual player count.


```lua
-- Fast lookup table keyed by Entity index, not ply object
local playerData = {}

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

function GetPlayerData(ply, key)
  local bucket = playerData[ply:EntIndex()]
  return bucket and bucket[key]
end
```

Reason: Indexing a plain Lua table by integer entity index avoids metatable lookups and the overhead of accessing entity Lua fields (which go through the Entity metatable), yielding a single hash lookup per access instead of the property-surface indirection that `ply.someField` incurs.


Answer must contain 0 through 1 candidate loops.

```lua
-- Faster: sequential number-indexed array
local fruits = { "apple", "banana", "cherry" }
for i = 1, #fruits do
  print(i, fruits[i])
end

-- Slower: string-keyed map
local fruits = { apple = true, banana = true, cherry = true }
for k, v in pairs(fruits) do
  print(k, v)
end
```

Reason: Sequential arrays (`{ [1]=x, [2]=y }`) are stored as flat contiguous memory in LuaJIT, enabling O(1) index access and cache-friendly traversal; string-keyed maps require hash table lookups with collision handling, and the JIT compiler can emit more efficient machine code for `#`-bounded array loops than for `pairs()` hash iteration.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate r, g, b, a integers avoids allocating a Color table and the internal unpack/type-check overhead, reducing GC pressure and function-call cost in hot draw loops.


```lua
local result = sql.Query("SELECT steamid, name FROM players WHERE steamid = '" .. sql.SQLStr(steamid) .. "'")
if result then
    print("Player: " .. result[1]["name"])
end
```
Reason: SQLite is embedded in-process with zero network latency, while remote MySQL adds TCP round-trip overhead on every query.


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

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

Reason: Weak-key table lets GC reclaim entries for disconnected players; lookup is O(1) and avoids repeated SteamID() overhead on the hot path.


```lua
-- Slow: O(n²) — each .. copies every prior character into a new string
local function slowConcat(parts)
    local s = ""
    for i = 1, #parts do
        s = s .. parts[i]
    end
    return s
end

-- Fast: O(n) — table.concat allocates once and copies characters once
local function fastConcat(parts)
    local t = {}
    for i = 1, #parts do
        t[i] = parts[i]
    end
    return table.concat(t)
end
```

Reason: `table.concat` copies all characters in a single pass (O(n)), while `..` creates a new string and copies all prior characters on every concatenation (O(n²)).


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

Reason: `draw.RoundedBox` incurs function-call and parameter-parsing overhead even with radius 0; `surface.DrawRect` is the thin built-in wrapper that draws a filled rect with no rounding logic.


```lua
-- In your Paint hook, cache the font outside the hook:
local cachedFont = "DermaDefault"

function PANEL:Paint(w, h)
    surface.SetFont(cachedFont)
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello World")
end
```

Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` avoids the per-frame overhead of `draw.DrawText` (which recomputes alignment) and `draw.SimpleTextOutlined` (which draws the string multiple times for the outline); caching the font string and calling `SetFont` once per frame rather than per draw call is the key win.


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

Reason: The `#` operator is the standard Lua length operator for sequential tables.


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

-- Faster for sequential tables (no shared references):
t = {}

-- Slower — must iterate all keys:
table.Empty(t)
```

Reason: `table.Empty(t)` is O(n) — it iterates every key and sets it to nil — while `t = {}` is O(1) — a single empty-table allocation.


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

-- O(1) membership test instead of O(n) table.HasValue
if set[value] then
  -- exists
end
```

Reason: `table.HasValue` is O(n); building a hash set once gives O(1) lookups, faster for repeated checks.


```lua
-- FASTER: fields inside the constructor
local pos = { x = 0, y = 1, z = 2 }

-- SLOWER: fields assigned after
local pos = {}
pos.x = 0
pos.y = 1
pos.z = 2
```

Reason: The table constructor compiles to a single optimized VM instruction that populates the hash part during allocation, while post-construction assignment emits separate SETTABLE instructions each performing its own key hash and chain walk.


```lua
local el = t[math.random(#t)]
```

Reason: Direct index via `math.random` skips `table.Random`'s sequential-check and `pairs` iteration overhead.


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

Reason: Multiplication is the fastest primitive CPU operation; it avoids the overhead of `math.pow` (function-call dispatch, generic number coercion) and any table lookups.


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

Reason: `player.Iterator()` is the modern, allocation-free way to iterate all connected players in Garry's Mod.


```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 of all entities first.


```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 the specified hook event. The Think hook runs every frame, making it suitable for per-frame logic. The identifier "MyAddon.Think" uniquely names this hook registration for potential removal with `hook.Remove`.


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

Reason: `IsValid(ent)` returns false for NULL entities, removed entities, and nil, making it the standard guard before calling any entity methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming net message here
    local data = net.ReadTable() -- or whatever data types you expect
    print("Received MyAddon.Sync from " .. tostring(ply))
end)
```

Reason: In Garry's Mod, `net.Receive` registers a handler for a named net message. The callback receives the message length and the sending player (server-side) or nil (client-side).


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

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

Reason: Reusing a single Angle instance avoids allocation and GC pressure in the hot path. Setting fields directly is faster than `Angle(0,0,0)` which constructs a new object each call.


```lua
-- Flat local variable (preferred)
local config_color = Color(255, 0, 0)

-- Read
local c = config_color
```

Reason: Local variables are resolved at compile-time with direct register access (OP_GETLOCAL), while nested table access requires multiple runtime hash lookups (OP_GETTABLE per level). For hot paths, locals avoid table traversal entirely.


```lua
-- Preferred: DarkRP var system
local jobName = ply:getDarkRPVar("job")

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

Reason: `getDarkRPVar("job")` uses DarkRP's optimized variable system with proper caching and change hooks, while `GetNWString` is generic networking with no DarkRP integration.


```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 the standard optimization for threshold checks in GMod Lua.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- Process each entity
    print(ent:GetClass())
end
```

Reason: `ents.GetAll()` is the wiki-recommended method for iterating all entities in Garry's Mod; it returns a sequential table allowing efficient `ipairs` iteration without creating intermediate tables.


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

Reason: FindInSphere uses the engine's spatial partitioning (Octree/BSP) for O(log n) radius queries, making it significantly faster than FindInPVS for proximity checks around a player.


```lua
local function FindPlayersInSphere(pos, radius)
    local radiusSqr = radius * radius
    local players = {}
    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 (typically ≤128) vs `ents.FindInSphere` which checks all entities (often thousands), and `DistToSqr` avoids the expensive square root.


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

Reason: In LuaJIT (used by Garry's Mod), numeric `for` loops are heavily optimized — the loop variable stays in a register, bounds are checked once, and the JIT compiles them to tight machine code. `while` loops with manual increments generate more bytecode and inhibit trace compilation.


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

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

-- In your hook receiver:
hook.Add("CustomTick", "MyTickHandler", function(players)
    for _, ply in ipairs(players) do
        -- per-player logic here
    end
end)
```

Reason: hook.Run has overhead iterating registered hooks; one call with a table avoids N-1 redundant iterations.


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

    draw.SimpleText("HP: " .. hp, "Trebuchet24", 10, 10, Color(255, 255, 255))
    draw.RoundedBox(0, 10, 40, hp * 2, 20, Color(255, 0, 0))
    draw.SimpleText(hp .. " / " .. ply:GetMaxHealth(), "Trebuchet18", 10, 65, Color(200, 200, 200))
end)
```

Reason: Caching `LocalPlayer():Health()` in a local variable avoids three redundant C++ method calls and object lookups per frame.


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

hook.Add("HUDPaint", "Example", function()
    surface.SetDrawColor(white)
    -- draw calls
end)
```

Reason: Creating a new Color object every frame allocates memory and triggers garbage collection. Caching it once outside the hook avoids repeated allocation.


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

Reason: Caching `math.sin` in a local variable avoids repeated global table lookups (`math` → `sin`) on each iteration, which is significantly faster in Lua's VM.


```lua
local lp = LocalPlayer()

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

-- Usage: use `lp` instead of `LocalPlayer()`
```

Reason: Caching LocalPlayer() in a variable and updating it via Think hook avoids the expensive C++ lookup on every call while staying valid after player spawns or map changes.


```lua
function PlayersLookingAtEachOther(ply1, ply2)
    if not IsValid(ply1) or not IsValid(ply2) then return false end
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    -- Dot product near -1 means facing each other
    return aim1:Dot(aim2) < -0.5
end
```

Reason: Dot product of aim vectors is cheaper than angle calculations; negative dot product indicates opposing directions, and threshold -0.5 (~120°) gives a generous "roughly looking at" cone.


```lua
local function SomeHelper(ply)
    -- implementation
end

-- Preferred call style
SomeHelper(ply)
```

Reason: Direct function calls avoid the table lookup (`ply.SomeHelper`) that method syntax (`ply:SomeHelper()`) requires, giving a negligible but measurable edge in tight loops.


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

Reason: `Msg` writes directly to the console without the overhead of `print`'s argument formatting, timestamping, and `tostring` coercion on each arg. In a hot path, avoid string concatenation entirely by logging less frequently or buffering.


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

-- Fastest: numeric for loop
for i = 1, #tbl do
    local v = tbl[i]
    -- process v
end
```

Reason: In LuaJIT (used by Garry's Mod), numeric `for i = 1, #tbl do` compiles to highly optimized machine code with direct indexed access, zero iterator overhead, and predictable memory access patterns. `ipairs` adds a function call per iteration; `pairs` traverses the hash table.


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

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

-- Usage: chained, zero-allocation intermediate
local players = { {name="a", alive=true}, {name="b", alive=false}, {name="c", alive=true} }
local aliveNames = map(filter(players, function(p) return p.alive end), function(p) return p.name end)
```

Reason: Plain loops with preallocated tables avoid fn's closure overhead, per-iteration table allocations, and iterator protocol costs.


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

local function rebuildCache()
    cachedPlayers = player.GetAll()
    cacheVersion = cacheVersion + 1
end

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

hook.Add("Think", "PlayerCache_Usage", function()
    local currentVersion = cacheVersion
    local players = cachedPlayers

    -- Use players here; it only rebuilds when someone joins/leaves
    for i = 1, #players do
        local ply = players[i]
        -- per-player logic
    end
end)
```
Reason: Caches `player.GetAll()` in a table and increments a version counter only on join/leave hooks, so the Think hook reads a stable reference without per-tick allocation.


```lua
local playerData = {}

function GetPlayerData(ply)
    local id = ply:SteamID64()
    return playerData[id]
end

function SetPlayerData(ply, key, value)
    local id = ply:SteamID64()
    playerData[id] = playerData[id] or {}
    playerData[id][key] = value
end
```

Reason: Direct table lookup by SteamID64 avoids the player entity metatable overhead on every read, and keeps data isolated from the entity's native fields.


```lua
-- Sequential array (fast iteration)
local colors = {"red", "green", "blue"}
for i = 1, #colors do
    print(colors[i])
end

-- String-keyed map (slow iteration)
local colors_map = {r = "red", g = "green", b = "blue"}
for k, v in pairs(colors_map) do
    print(v)
end
```

Reason: Sequential arrays use contiguous memory layout with O(1) length access and optimized `ipairs`/numeric loops, while string-keyed maps require hash table lookups and `pairs` iteration overhead.


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

Reason: Passing separate r,g,b,a numbers avoids allocating a Color table each frame, reducing GC pressure and allowing LuaJIT to optimize the call as a direct C function invocation with primitive arguments.


```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, no connection pooling overhead, and no authentication latency — critical for per-tick or per-player-action queries on a single server.


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

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

Reason: Weak-keyed table automatically cleans up when players disconnect, avoiding memory leaks while providing O(1) lookup after first call.


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

Reason: `table.concat` is O(n) while repeated `..` is O(n²) due to string immutability creating new allocations each iteration.


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

Reason: `surface.DrawRect` is the direct low-level call for axis-aligned rectangles, avoiding the `draw.RoundedBox` wrapper overhead (radius check, color handling, and extra function call).


```lua
local font = "DermaDefault"
local str  = "Hello, world!"
local col  = Color(255, 255, 255)

hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(font)
    surface.SetTextColor(col.r, col.g, col.b, col.a)
    surface.SetTextPos(100, 100)
    surface.DrawText(str)
end)
```

Reason: `surface.DrawText` avoids the markup parsing, alignment logic, and internal font lookups that `draw.DrawText`/`draw.SimpleTextOutlined` perform each call, making it the lowest-overhead path for static single-line strings.


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

Reason: The `#` operator is Lua's built-in length operator for sequential tables (arrays), returning the last integer index with a non-nil value.


```lua
t = {}
```

Reason: `t = {}` allocates a new empty table (fast constant-time operation) and lets the old table be garbage collected later. `table.Empty(t)` must iterate and nil out every key in the existing table, which is O(n) and slower for large sequential tables in LuaJIT.


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

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

Reason: table.HasValue iterates the entire array (O(n)), while key lookup in a hash table is constant time (O(1)).


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

Reason: Table constructors with known fields are allocated once with optimal size hints, avoiding multiple SETTABLE operations and potential rehashing that occurs when assigning fields after `{}`.


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

Reason: `math.random(#tbl)` directly indexes the table without `table.Random`'s internal type checks and iterator overhead, making it ~3-5x faster for sequential tables.


```lua
local result = x * x
```
Reason: `x * x` compiles to a single MUL opcode, while `x^2` or `math.pow(x,2)` incur function call overhead or bytecode for the power operator.


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

Reason: `player.Iterator()` is the modern, memory-efficient way to iterate players in Garry's Mod — it avoids allocating a new table on each call unlike `player.GetAll()`.


```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 of all entities, avoiding the memory overhead of `ents.GetAll()` or `ents.FindByClass()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your think logic here
end)
```
Reason: This registers a callback on the Think hook using the unique identifier "MyAddon.Think" as requested.


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

Reason: `IsValid(ent)` returns false for nil, NULL entities, and entities that have been removed, making it the standard safety check before calling methods on entity references in Garry's Mod.


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

Reason: `net.Receive` is the standard Garry's Mod API for registering a callback that fires when a specific net message is received from the client (or server, depending on realm). The callback receives the message length in bytes and the player who sent it.


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

-- In hot path:
local ang = zeroAngle
```

Reason: Reusing a pre-allocated Angle avoids the overhead of `Angle()` constructor calls, memory allocation, and garbage collection pressure in tight loops.


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

-- Read
local c = myaddon_config_color
```

Reason: Local variables are resolved at compile time with a single register lookup, while nested tables require multiple runtime hash lookups (myaddon → config → color) and global lookups hit the _G table.


```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("job")` is the DarkRP-specific accessor that reads the synchronized DarkRP variable directly, avoiding the generic NWString overhead and ensuring compatibility with DarkRP's variable system.


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

Reason: `DistToSqr` avoids the expensive square root operation by comparing squared distances directly against the squared threshold.


```lua
for _, ent in ents.Iterator() do
    -- Process each entity here
    print(ent:GetClass())
end
```

Reason: `ents.Iterator()` is the wiki-recommended efficient iterator that yields entities one at a time without allocating a full table, making it memory-efficient for large entity counts.


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

Reason: `ents.FindInSphere` uses the engine's spatial partition (octree/BSP) for O(log n) radius checks, avoiding PVS traversal overhead and AABB tests; benchmarks consistently show it 3–10× faster than `FindInBox` or `FindInPVS` for typical "near player" radii (128–512 units).


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local players = player.GetAll()
    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 players (not all entities), and `DistToSqr` avoids the square root calculation, making it significantly faster than `ents.FindInSphere` + filtering when entity counts are high.


```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 compiles numeric `for` loops into highly optimized machine code with a single loop header, eliminating bounds checks and increment overhead that `while` loops require.


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

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

Reason: hook.Run has internal overhead (hook table lookup, argument packing, pcall protection). Calling it once with a table of all players avoids N-1 redundant hook dispatches per tick, reducing function call overhead and garbage from temporary argument tables.


```lua
hook.Add("HUDPaint", "OptimizedHealthDisplay", function()
    local hp = LocalPlayer():Health()

    -- Draw call 1
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, Color(255, 255, 255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)

    -- 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, ScrH() / 2, Color(255, 0, 0), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
    end
end)
```

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


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

hook.Add("HUDPaint", "Example", function()
    surface.SetDrawColor(white)
    -- draw calls
end)
```

Reason: Creating Color objects allocates memory and triggers garbage collection; reusing a single cached instance eliminates per-frame allocation overhead.


```lua
local sin = math.sin

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

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


```lua
local LocalPlayer = LocalPlayer

-- Usage
local ply = LocalPlayer()
```

Reason: Caching `LocalPlayer` as a local variable avoids the global table lookup and function call overhead on every access. The local reference resolves once at load time, then direct variable access is used thereafter.


```lua
function PlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- ~45 degrees, adjust 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: Dot product of normalized vectors gives cosine of angle directly; comparing against a threshold (e.g., 0.7 ≈ 45°) avoids expensive acos while checking both players face each other.


```lua
ply:SomeHelper()
```
Reason: `ply:SomeHelper()` is idiomatic for methods on entities, avoids a global table lookup when the helper is in the entity metatable, and compiles to identical bytecode as `SomeHelper(ply)` when the function is defined the same way.


```lua
Msg("debug: " .. value .. "\n")
```

Reason: `Msg` 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} -- large sequential array

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

Reason: Numeric for avoids iterator overhead and uses direct index access; ipairs adds iterator function calls; pairs iterates all keys including non-array parts.


```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 table avoids closure allocation per element, eliminates fn.Compose/fn.Filter call overhead, and uses numeric indexing for JIT-friendly hot paths.


```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_ExampleUsage", function()
    if not cacheValid then rebuildCache() end
    for _, ply in ipairs(cachedPlayers) do
        -- your per-player logic here
    end
end)
```

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


```lua
-- Use a separate table keyed by player entity for O(1) reads without metatable overhead
local playerData = {}

-- Write
playerData[ply] = playerData[ply] or {}
playerData[ply].someField = value

-- Read (faster than ply.someField)
local val = playerData[ply] and playerData[ply].someField
```

Reason: Direct table access avoids the entity metatable's `__index`/`__newindex` metamethods and C++ boundary crossings that `ply.someField` incurs on every read/write.


OpenCode returned no answer text; error: "Streaming response failed"


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

Reason: Passing separate r,g,b,a numbers avoids allocating a Color table object on every call, reducing 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) avoids network round-trips and external process overhead, giving lower latency for single-server workloads.


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

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

Reason: Strings are immutable in Lua; each `..` creates a new string copying all prior content. `table.concat` allocates once and copies each piece exactly once.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect avoids draw.RoundedBox's internal radius checks and function overhead, directly issuing the rectangle draw call.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```

Reason: `surface.DrawText` bypasses the `draw` library's overhead (font fallback, shadow/outline processing, alignment calculations) and directly submits glyph quads to the render queue, making it the lowest-latency path for per-frame single-line text.


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

Reason: In Lua (including Garry's Mod's LuaJIT), the `#` operator is the standard and preferred way to get the length of a sequential array-like table. It returns the highest integer index with a non-nil value.


```lua
t = {}
```

Reason: `t = {}` allocates a new empty table (O(1)) and lets the old table be garbage collected, while `table.Empty(t)` must iterate and nil out every key (O(n)).


```lua
-- Slow: O(n) linear search
local list = { "a", "b", "c", "d" }
local function hasValueList(tbl, val)
    for _, v in ipairs(tbl) do
        if v == val then return true end
    end
    return false
end

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

-- Usage
print(hasValueList(list, "c"))  -- true
print(hasValueSet(set, "c"))    -- true
```

Reason: Hash set lookup is O(1) vs O(n) linear search; avoids function call overhead of table.HasValue.


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

Reason: Table constructors with known fields are faster because they allocate the table with the correct size upfront and populate it in a single operation, avoiding multiple hash table insertions and potential rehashing.


```lua
x * x
```
Reason: Direct multiplication compiles to a single VM opcode (MUL), while `x^2` or `math.pow(x,2)` invoke the pow metamethod or C function with call overhead. In tight loops, `x * x` is measurably faster.


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

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

Reason: `player.GetAll()` returns a sequential array, so `ipairs` is the correct iterator (not `pairs`). The `_` discards the numeric index since only the player entity is needed.


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

Reason: `ents.Iterator()` returns a stateless iterator that yields entities one at a time without materializing a full table of all entities in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your think logic here
end)
```
Reason: The `hook.Add` function registers a callback for the "Think" event with the unique identifier "MyAddon.Think", ensuring it runs every frame and can be removed later with `hook.Remove("Think", "MyAddon.Think")`.


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

Reason: `IsValid(ent)` returns false for nil, NULL entities, and entities that have been removed, preventing errors when calling methods on invalid references.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming net message here
    local data = net.ReadTable() -- or whatever data type you're sending
    -- Process data...
end)
```

Reason: This registers a server-side handler for the "MyAddon.Sync" net message using Garry's Mod's `net.Receive` API, which takes the message name and a callback function receiving the message length and the sending player.


```lua
-- Slow: allocates new object every call (GC pressure)
local function Slow()
    local ang = Angle()
    return ang
end

-- Fast: reuse single pre-allocated object
local zeroAng = Angle()
local function Fast()
    zeroAng:SetUnpacked(0, 0, 0)
    return zeroAng
end
```

Reason: Reusing a single Angle instance with `SetUnpacked` avoids allocation and GC churn in hot paths, while `Angle()` constructs a new object each call.


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

-- Read
local c = config_color
```

Reason: Local variables avoid global table lookups and nested indexing overhead; they resolve in a single VM register access.


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

Reason: DarkRP stores job info in DarkRPVars (networked vars with prediction), not generic NWStrings. `getDarkRPVar` is the correct accessor, handles nil safely, and avoids stringly-typed NetVar lookups.


```lua
local threshold = 100
if pos1:DistToSqr(pos2) < threshold * threshold then
    -- within threshold
end
```

Reason: `DistToSqr` avoids the expensive square root operation by comparing squared distances directly against the squared threshold.


```lua
for _, ent in ents.Iterator() do
    -- Process each entity here
    print(ent:GetClass())
end
```

Reason: `ents.Iterator()` is the wiki-recommended efficient iterator as it avoids creating a full table of all entities in memory, instead yielding entities one at a time via a Lua iterator function.


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

Reason: FindInSphere uses a simple spatial partition lookup with a single distance check per entity, making it the fastest built-in for radius queries around a player position in typical benchmarks.


```lua
local function FindPlayersInSphere(pos, radius)
    local radiusSqr = radius * radius
    local players = player.GetAll()
    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 players (typically <100) instead of all entities (often thousands), and DistToSqr avoids the expensive square root operation.


```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: Numeric `for` loops compile to dedicated VM bytecode (`FORPREP`/`FORLOOP`) with a single branch per iteration, while `while` loops require separate load, compare, branch, and increment instructions each iteration.


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

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

Reason: Single hook.Run avoids repeated hook table lookups and function call overhead per player; the hook system iterates callbacks once internally.


```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(255, 255, 255))

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

    -- Draw call 3
    if hp <= 25 then
        draw.SimpleText("LOW HEALTH", "DermaDefaultBold", 10, 55, Color(255, 0, 0))
    end
end)
```

Reason: Caches `LocalPlayer():Health()` in a local variable `hp` once per frame instead of calling the method three times, avoiding redundant function calls and virtual method lookups.


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

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

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


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

Reason: Caching `math.sin` in a local variable avoids repeated global table lookups (`math` → `sin`) inside the hot loop, reducing per-iteration overhead.


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

Reason: LocalPlayer() does a global lookup and internal C++ call every time; caching it in a local variable avoids that overhead and is safe as long as you re-check validity when the player could have disconnected or changed.


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

Reason: Uses cheap dot products on normalized vectors instead of expensive angle calculations; `aim1:Dot(toTarget) > tolerance` checks if ply1 aims toward ply2 within the angular threshold, and the second check does the reverse for ply2.


```lua
SomeHelper(ply)
```
Reason: In LuaJIT (used by Garry's Mod), `SomeHelper(ply)` avoids the table lookup for the method on `ply` and compiles to a direct call; the `: ` sugar adds an extra `ply.SomeHelper` lookup that, while often inlined, is strictly more work. For a helper you control, the function form is marginally faster and clearer about ownership.


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

Reason: `MsgN` writes directly to the console without the formatting overhead, timestamp, and newline handling that `print` performs, making it significantly faster in hot paths.


```lua
local t = {1, 2, 3, 4, 5}
for i = 1, #t do
    local v = t[i]
    -- use v
end
```

Reason: Numeric for avoids iterator function calls and LuaJIT compiles it to tight machine code; ipairs/pairs add iterator overhead and prevent some JIT optimizations.


```lua
-- DarkRP fn style (slower due to function call overhead)
local result = fn.Compose{fn.Filter(function(x) return x > 5 end), fn.Map(function(x) return x * 2 end)}(data)

-- Faster: single loop, no function calls
local result = {}
for i = 1, #data do
    local v = data[i]
    if v > 5 then
        result[#result + 1] = v * 2
    end
end
```

Reason: Plain loops avoid function call overhead and closure allocations; LuaJIT compiles them to efficient bytecode while fn.Compose creates intermediate tables and invokes multiple functions per element.


```lua
local cachedPlayers = {}

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

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

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

Reason: Replaces O(n) `player.GetAll()` per tick with O(1) cached table iteration, updating only on join/leave events via `PlayerInitialSpawn` and `PlayerDisconnected` hooks.


```lua
local playerData = {}

-- Write
playerData[ply] = value

-- Read (fastest)
local value = playerData[ply]
```

Reason: Direct table lookup with player entity as key avoids entity metatable overhead and is a single hash lookup. Local `playerData` reference eliminates global scope access.


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

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

Reason: Sequential arrays use contiguous memory and optimize to tight C loops via LuaJIT's trace compiler; string-keyed maps require hash lookups and prevent JIT compilation of the iteration.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate r,g,b,a arguments avoids allocating a Color table and the unpacking overhead inside SetDrawColor, saving ~15-20% in hot draw loops.


```lua
-- Using GMod's built-in sql library (SQLite)
local result = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
```

Reason: Local SQLite via GMod's sql library eliminates network round-trips and connection overhead, making reads/writes significantly faster than remote MySQL for a single-server setup.


```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: Caches SteamID by entity index (stable per session), clears on player disconnect, avoids repeated C++ bridge calls.


```lua
local pieces = {}

for i = 1, 10000 do
    pieces[i] = "piece " .. i .. "\n"
end

local result = table.concat(pieces)
```

Reason: Repeated `..` concatenation creates a new string allocation each iteration (O(n²)), while `table.concat` collects references and does one allocation (O(n)).


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

Reason: `surface.DrawRect` bypasses the rounding logic entirely, avoiding the internal corner-table allocation and vertex buffering that `draw.RoundedBox` performs even at radius 0. It maps directly to the render library's immediate-mode quad path.


```lua
-- Fastest: surface.DrawText with font set ONCE outside the hook
local font = "DermaDefault"
local text = "Your string here"
local x, y = 100, 100

surface.CreateFont("MyCachedFont", { font = "Roboto", size = 16, weight = 500 })

hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont("MyCachedFont")
    surface.SetTextPos(x, y)
    surface.SetTextColor(255, 255, 255, 255)
    surface.DrawText(text)
end)

-- If outline needed, draw.SimpleTextOutlined is faster than draw.DrawText
hook.Add("HUDPaint", "FastOutlinedText", function()
    draw.SimpleTextOutlined(text, "MyCachedFont", x, y, color_white, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, color_black)
end)
```

Reason: `surface.DrawText` avoids draw library overhead (alignment calc, wrapping, color table allocation). `draw.SimpleTextOutlined` is the fastest draw.* helper because it skips text wrapping and alignment logic that `draw.DrawText` performs every frame. Cache the font with `surface.CreateFont` once, never in the hook.


```lua
#myTable
```

Reason: In Lua (including Garry's Mod), the `#` operator returns the length of a sequential array-like table (a sequence). It works on tables with consecutive integer keys starting from 1.


```lua
t = {}
```

Reason: `t = {}` is O(1) — it allocates a new empty table and lets the old one be garbage collected. `table.Empty(t)` is O(n) — it must iterate and nil out every element individually.


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

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

Reason: `table.HasValue` iterates the entire array (O(n)), while a hash-set lookup uses the key directly (O(1)).


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

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

Reason: Table constructors pre-allocate the hash part with exact capacity, avoiding rehashing and multiple allocations.


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

Reason: `table.Random` iterates the entire table (O(n)), while direct index access with `math.random(#tbl)` is O(1) for sequential tables.


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

Reason: Multiplication (`x * x`) is faster than exponentiation (`x ^ 2` or `math.pow(x, 2)`) because it avoids function call overhead and the more complex exponentiation bytecode path. In tight loops, this micro-optimization matters.


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

Reason: `player.Iterator()` is the modern, idiomatic way to iterate players in Garry's Mod — it avoids creating a temporary table and works directly with the engine's internal player list.


```lua
local physIterator = ents.Iterator('prop_physics')
for ent in physIterator:Next() do
    -- Your code here
end
```

Reason: The `ents.Iterator()` method directly iterates over prop_physics entities without building a complete table of all entities in the map.


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

Reason: This registers the MyAddon.Think callback to execute on every game tick Think hook.


```lua
if ent and ent:IsValid() then
    -- Use ent
end
```
Reason: In Garry's Mod Lua, entities can become invalid when removed, so checking both existence and IsValid() prevents errors from using stale references.


```lua
net.Receive("MyAddon.Sync", function()
    -- Your message handling logic here
end)
```

Reason: This properly registers a net message handler for incoming "MyAddon.Sync" messages in Garry's Mod Lua using the net.Receive function.


```lua
local zeroAngle = Angle()

local function getFreshZeroedAngle()
    zeroAngle:Set(0, 0, 0)
    return zeroAngle
end
```

Reason: Reusing a pre-allocated Angle object and resetting it via Set() avoids the garbage collection overhead of creating Angle() instances in tight loops.


```lua
-- Flat local variable approach (preferred for frequently accessed settings)
local addon_color_red = 255
local addon_color_green = 0
local addon_color_blue = 0

local r = addon_color_red
```

Reason: Flat variables have minimal memory overhead and LuaJIT optimizes direct table access, while nested tables add unnecessary nested lookup complexity that can marginally reduce performance for frequently accessed configuration values.


```lua
local jobName = ply:GetDarkRPVar("job")  -- More reliable and recommended API
```

Reason: `ply:GetDarkRPVar("job")` is the preferred DarkRP API that provides better abstraction, handles job index conversion internally, and integrates with DarkRP's job management system more cleanly than directly accessing `GetNWString("job")`.


```lua
-- Preferred method: Compare squared distance instead of actual distance
local distanceSquared = (self - other):LengthSqr()
local thresholdSquared = threshold * threshold

if distanceSquared <= thresholdSquared then
    -- Vectors are within threshold
end
```

Reason: This avoids the expensive square root calculation by comparing squared distances, which is mathematically equivalent but more efficient.


```
for _, ent in ipairs(ents.GetAll()) do
  -- Do something with each entity
end
```

Reason: The official Garry's Mod Lua wiki recommends using `ents.GetAll()` for iterating through all entities as it's the most straightforward and widely-used method, providing direct access to the entire entity list while remaining simple and readable.


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

Reason: `FindInSphere` is consistently one of the fastest built-in FindIn* methods in Garry's Mod benchmarks, offering optimal performance for radius-based proximity queries while avoiding the overhead of FindInPVS's vis-leaf calculations.


```lua
local function findPlayersInSphere(pos, radius)
    local nearby = {}
    local playerEnts = ents.FindByClass("player")
    local minDistSq = radius * radius

    for i = 1, #playerEnts do
        local ply = playerEnts[i]
        local delta = ply:GetPos() - pos
        local distSq = delta.x * delta.x + delta.y * delta.y + delta.z * delta.z

        if distSq <= minDistSq then
            nearby[#nearby + 1] = ply
        end
    end

    return nearby
end
```

Reason: The optimized approach uses direct vector math and avoids the inefficient filtering of `ents.FindInSphere`'s complete results, reducing both memory allocation and processing overhead by only checking players that exist in the sphere.


```lua
-- For loop (generally faster in Garry's Mod)
for i = 1, n do
    print(i)
end

-- While loop (generally slower in Garry's Mod)
local i = 1
while i <= n do
    print(i)
    i = i + 1
end
```

Reason: For loops are optimized in Garry's Mod's Lua VM, reducing bytecode instruction overhead compared to while loops which require more frequent condition checks.


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

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

Reason: The single batch call with all players reduces function call overhead and memory allocation churn, making it faster than calling hook.Run once per player.


```
local player = LocalPlayer()
local health = player:Health()

draw.DrawText("HP: " .. health, 10, 10, Color(255, 255, 255, 255), 0)
draw.DrawText("Health: " .. health, 10, 30, Color(255, 255, 255, 255), 0)
draw.DrawText(string.format("Current Health: %d", health), 10, 50, Color(255, 255, 255, 255), 0)
```

Reason: Stored player and health in locals to avoid repeated method calls and improve performance.


```lua
local white = Color(255, 255, 255)
surface.SetDrawColor(white)
```

Reason: Creating the color once outside the loop avoids repeated object allocation.


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

Reason: Reduce repeated global variable lookups by caching the function reference in a local variable.


```lua
local localPlayer = LocalPlayer()

-- Use the cached reference instead of calling LocalPlayer() every time
if localPlayer:Alive() then
    local pos = localPlayer:GetPos()
    print("Player position:", pos.x, pos.y, pos.z)
end
```

Reason: Caching LocalPlayer() in a local variable eliminates repeated function lookups.


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

```lua
local function are_players_looking_at_each_other(lp, other)
    local lp_vec = lp:GetAimVector()
    local other_vec = other:GetAimVector()

    local lp_to_other = (other:GetPos() - lp:GetPos()):GetNormalized()
    local other_to_lp = (lp:GetPos() - other:GetPos()):GetNormalized()

    local threshold = 0.3

    local looking_towards = lp_vec:Dot(lp_to_other) > threshold
    local other_looking_back = other_vec:Dot(other_to_lp) > threshold

    return looking_towards and other_looking_back
end
```

Reason: Using dot product with normalized direction vectors is cheaper than math.acos(angle_between) for checking rough alignment of aim directions.```lua
local function are_players_looking_at_each_other(lp, other)
    local lp_vec = lp:GetAimVector()
    local other_vec = other:GetAimVector()

    local lp_to_other = (other:GetPos() - lp:GetPos()):GetNormalized()
    local other_to_lp = (lp:GetPos() - other:GetPos()):GetNormalized()

    local threshold = 0.3

    local looking_towards = lp_vec:Dot(lp_to_other) > threshold
    local other_looking_back = other_vec:Dot(other_to_lp) > threshold

    return looking_towards and other_looking_back
end
```

Reason: Using dot product with normalized direction vectors is cheaper than math.acos(angle_between) for checking rough alignment of aim directions.


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

Reason: Both styles have identical performance as they're syntactic sugar in Lua; use the method syntax (`ply:SomeHelper()`) for better readability and to match how helper functions are typically defined.


```lua
local debug = {}

function debug.msg(msg)
    Msg(msg)
end

function debug.buffer()
    local buffer = {}
    function debug.buffer.add(msg)
        buffer[#buffer + 1] = msg
    end
    function debug.buffer.flush()
        for i, msg in ipairs(buffer) do
            Msg(msg)
        end
        buffer = {}
    end
    return debug.buffer
end
```

Reason: Msg is faster than print in Garry's Mod as it doesn't process colors or formatting, and buffering reduces the number of write operations.


```lua
-- Using ipairs
local start = SysTime()
for i, v in ipairs(t) do
    local _ = v
end
local ipairs_time = SysTime() - start

-- Using pairs (slowest)
local start = SysTime()
for i, v in pairs(t) do
    local _ = v
end
local pairs_time = SysTime() - start

-- Using numeric for (fastest)
local start = SysTime()
for i = 1, #t do
    local _ = t[i]
end
local numeric_time = SysTime() - start
```

Reason: Numeric for loop is fastest for sequential tables, followed by ipairs, with pairs being slowest due to key checking overhead.


```
-- Fast list transforms using native Lua patterns

-- Filter operation using array loop and table.insert for speed
local function filter_fast(pred, tbl)
    local result = {}
    for i = 1, #tbl do
        if pred(tbl[i]) then
            result[#result + 1] = tbl[i]
        end
    end
    return result
end

-- Map operation using direct array iteration
local function map_fast(func, tbl)
    local result = {}
    for i = 1, #tbl do
        result[i] = func(tbl[i])
    end
    return result
end

-- Chain operation without creating intermediate tables
local function each_fast(func, tbl, ...)
    for i = 1, #tbl do
        func(tbl[i], ...)
    end
end

-- Example: Process weapons with chain of filters and maps
function process_weapons_fast(weapons)
    local common_weapons = filter_fast(function(w) return w.common == true end, weapons)
    local named_weapons = map_fast(function(w) return w.name or "Unknown" end, common_weapons)

    local output = {}
    each_fast(function(name, arr) arr[#arr + 1] = name end, named_weapons, output)
    return output
end
```

Reason: Native Lua array iteration with manual table construction avoids fn combinator overhead and improves performance.


```lua
local cachedPlayers = {}

function RefreshPlayerCache()
    cachedPlayers = {}
    for _, ply in ipairs(player.GetAll()) do
        cachedPlayers[ply:SteamID()] = ply
    end
end

function InitializePlayerCache()
    RefreshPlayerCache()
end

hook.Add("Initialize", "PlayerCache_Init", InitializePlayerCache)
hook.Add("PlayerSpawned", "PlayerCache_Refresh", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "PlayerCache_Refresh", RefreshPlayerCache)

function Think_UseCachedPlayers()
    for _, ply in pairs(cachedPlayers) do
        if not ply or not ply:IsValid() then
            RefreshPlayerCache()
            return
        end
    end
end

hook.Add("Think", "Think_UseCachedPlayers", Think_UseCachedPlayers)
```

Reason: This caches all players once and only refreshes when join/disconnect events occur, eliminating the O(n) iteration of `player.GetAll()` on every tick.