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

Reason: `ents.Iterator` returns a direct iterator that yields matching entities one at a time without materializing the full entity list.


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

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

Reason: Pre-allocating the Color table outside the paint loop avoids creating a new userdata every frame, eliminating repeated allocations on a hot path.


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

Reason: `Dot` avoids the square root `DistanceSqr`/`Distance` would give; squaring the threshold is cheaper than any sqrt.


```lua
local ply = LocalPlayer()

function SomeThink()
    -- use 'ply' here instead of calling LocalPlayer() again
end
```

Reason: Caching LocalPlayer() in a local variable avoids repeated C++→Lua boundary crossings and hash-table lookups on the global table, giving a constant-time reference that stays valid as long as the player entity does.


```lua
function PlayersFaceEachOther(ply1, ply2)
  local fwd1 = ply1:GetAimVector()
  local fwd2 = ply2:GetAimVector()
  local to1 = (ply1:EyePos() - ply2:EyePos()):GetNormalized()
  local to2 = -to1
  return fwd1:Dot(to2) > 0.4 and fwd2:Dot(to1) > 0.4
end
```

Reason: The dot product of each player's aim vector against the direction toward the other player directly measures how much they're looking at each other; threshold ~0.4 (~66 degrees) is a cheap cosine check that avoids any trig, and requiring both directions exceeds the threshold ensures mutual face-to-face alignment without acos overhead.


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

Reason: Caching a library function in a local avoids repeated global table lookups, which is the single cheapest micro-opt for hot Lua loops.


```lua
-- Allocate once, reuse everywhere
local ZERO_ANGLE = Angle(0, 0, 0)

-- In your hot function, copy instead of constructing:
local function doWork()
    local ang = ZERO_ANGLE -- read-only reference (safe if you never mutate it)
    -- or, if you need a mutable copy:
    local ang = Angle(ZERO_ANGLE) -- still faster than Angle(0,0,0) due to no table rehash
end

-- Best: avoid Angle entirely when you only need yaw
local ZERO_VEC = Vector(0, 0, 0) -- some APIs accept a vector instead
```

Reason: Reusing a cached `Angle` reference avoids repeated metatable lookups, table allocation, and GC pressure, making it measurably faster than `Angle(0,0,0)` on every call in tight loops.


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

-- FASTER: hook.Run called once per tick, iteration inside the hook
hook.Run("CustomLogic", player.GetAll())
```

Reason: Each `hook.Run` lookup iterates the hook table and calls every registered function — calling it once avoids N-1 redundant table scans and function dispatches, so the hook author handles iteration internally.


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

    draw.RoundedBox(6, 10, 10, 200, 30, Color(0, 0, 0, 200))
    draw.RoundedBox(6, 10, 10, math.Clamp(hp / 100, 0, 1) * 200, 30, Color(255, 0, 0))
    draw.SimpleText(hp, "DermaLarge", 110, 25, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end)
```

Reason: Caching `LocalPlayer():Health()` into a local variable once avoids two redundant entity lookups and method calls per frame, reducing overhead on the hot draw path.


```lua
-- Preferred: uses DarkRP's own data layer instead of the networked string
local jobName = ply:Team() and team.GetName(ply:Team()) or "Unknown"
```

Reason: DarkRP stores the job as a team via SetTeam, so `team.GetName(ply:Team())` reads the authoritative local value instead of relying on a NWString that can be nil, delayed, or spoofed.


File receiver satisfies 6/13 confinement checks.

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

net.Receive("MyAddon.ReadUpload", function(len, ply)
    if not IsValid(ply) or not ply:IsSuperAdmin() then return end

    local raw = net.ReadString()
    if not raw or #raw == 0 or #raw > 64 then return end

    if not string.match(raw, "^[%w%.%-_]+$") then return end

    local path = "myaddon/uploads/" .. raw
    local fh = file.Open(path, "rb", "DATA")
    if not fh then return end

    local size = math.min(fh:Size(), 65536)
    local data = fh:Read(size)
    fh:Close()

    if not data then return end

    consume(data)
end)
```

Reason: Superadmin-only guard, 64-char max read from net, strict ASCII-segment allowlist via `%w%.%-_` (letters, digits, dot, hyphen, underscore) with anchoring to block path traversal, `file.Open` on the DATA path, capped 65536-byte read, explicit close, nil check, then `consume(data)`.


Does not use compact typed fields with targeted net.Send recipients.

```lua
local MSG_NAME = "MyStateMsg"

if SERVER then
    util.AddNetworkString(MSG_NAME)

    local band = bit.band
    local bor = bit.bor
    local rshift = bit.rshift
    local lshift = bit.lshift

    function SendPlayerState(state, amount, recipients)
        if not recipients or #recipients == 0 then return end
        local packed = bor(band(state, 0x7), lshift(band(amount, 0x3FF), 3))
        net.Start(MSG_NAME)
            net.WriteUInt(packed, 13)
        net.Send(recipients)
    end
end

if CLIENT then
    net.Receive(MSG_NAME, function()
        local packed = net.ReadUInt(13)
        local state = band(packed, 0x7)
        local amount = band(rshift(packed, 3), 0x3FF)
    end)
end
```

Reason: Packs state (0..7, 3 bits) and amount (0..1000, 10 bits) into a single 13-bit UInt, eliminating table serialization and minimizing per-message overhead; `net.Send` with an explicit recipient table restricts fanout server-side without broadcast or round-robin.


Uses IsValid for entity/object validity.

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

Reason: `IsValid` returns `false` when the entity has been removed or was never a valid object, preventing method calls on a stale/nil reference.


Caches stable render resources and derives per-frame values once.

```lua
local mat = Material("icon16/heart.png")
local col = Color(255, 50, 50)

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

    local hp = ply:Health()
    if hp <= 0 then return end

    surface.SetDrawColor(col)
    surface.SetMaterial(mat)
    surface.DrawTexturedRect(10, 10, 16, 16)

    draw.SimpleText(
        tostring(hp),
        "DermaLarge",
        32, 10,
        col,
        TEXT_ALIGN_LEFT,
        TEXT_ALIGN_TOP
    )
end)
```

Reason: Material and color are cached at load time to avoid per-frame allocations; LocalPlayer is called once and guarded; health is read once into a local; repeated draws use the pre-allocated color table.


```lua
local color = myaddon.config.color  -- cache once at load
print(color)                        -- fast register read
```
Reason: Lua locals live in VM registers and are the fastest access path; each dot in `myaddon.config.color` forces a separate table lookup, making nested reads measurably slower on hot paths.


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

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

Reason: `ply:SomeHelper()` is sugar for `ply.SomeHelper(ply)`, which forces a metatable lookup on the entity every call — and GMod entities have deep metatable chains — while a direct local-function call avoids that entirely.


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

Reason: `hook.Add` registers a callback on the named hook with the given unique identifier, and `Think` fires every client frame.


```lua
local sum = 0
for i = 1, n do
  sum = sum + i
end
```
Reason: The numeric `for` loop compiles to the dedicated `FORPREP`/`FORLOOP` bytecode pair with the counter held in a local register, while a `while` loop must emit separate instructions for comparison, body, increment, and the jump back, making the `for` form fewer instructions per iteration in Luau.


```lua
local t = { /* large sequential array of numbers */ }

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

Reason: Numeric for avoids iterator function overhead and LuaJIT optimizes direct array indexing better than ipairs/pairs iteration.


Does not define the integer Power datatable variable.

```lua
NetworkVar("Int", 0, "Power")
```

Reason: `NetworkVar("Int", ...)` is Garry's Mod's built-in entity state primitive for named, indexed, predicted integers — more efficient than individual `SetNWInt`/`GetNWInt` calls and automatically handles prediction and networking.


Receiver satisfies 9/15 per-player budget checks.

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

local RATE = 20
local WINDOW = 1
local budgets = {}

local function GetBudget(ply)
    local sid = ply:SteamID64()
    if not budgets[sid] then
        budgets[sid] = { count = 0, reset = CurTime() + WINDOW }
    end
    local b = budgets[sid]
    if CurTime() >= b.reset then
        b.count = 0
        b.reset = CurTime() + WINDOW
    end
    return b
end

net.Receive("MyAddon.Action", function(len, ply)
    if len > 64 then return end

    local b = GetBudget(ply)
    if b.count >= RATE then return end
    b.count = b.count + 1

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    perform(ent)
end)

hook.Add("PlayerDisconnected", "MyAddon.CleanupBudget", function(ply)
    budgets[ply:SteamID64()] = nil
end)
```

Reason: Sliding-window rate limiter with 20-msg cap per 1 s, early rejection on oversized payloads and over-budget, entity validation, single pool, and cleanup on disconnect.


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

Reason: `player.GetAll()` iterates a tiny list (server slot cap, typically 64) with a cheap squared-distance check, while `ents.FindInSphere` scans every entity in the map (brushes, ragdolls, props, effects — thousands) and then you still filter; the manual approach is O(players) not O(all entities).


Answer must contain 0 through 0 candidate loops.

```lua
local center = ply:GetPos()
local radius = 512
local ents = ents.FindInSphere(center, radius)
-- filter by class, model, etc. as needed
for _, ent in ipairs(ents) do
    -- process nearby entity
end
```
Reason: `ents.FindInSphere` is consistently one of the fastest spatial queries in common GMod benchmarks (e.g. Garry's Mod Lua optimisation threads) because it uses a single radius check on the engine's BSP, avoiding the overhead of PVS sets or AABB box construction.


Does not implement the bounded sender-owned chunk receiver.

```lua
net.Receive("MyAddon.Chunk", function(len, ply)
    local transferId = net.ReadUInt32()
    local chunkIndex = net.ReadUInt16()
    local chunkSize = net.ReadUInt16()

    local transfer = MyAddon.transfers[ply]
    if not transfer or transfer.id ~= transferId then return end

    if chunkIndex < 1 or chunkIndex > 64 then return end
    if transfer.chunks[chunkIndex] then return end
    if chunkSize > 24000 then return end
    if chunkSize > net.BytesLeft() then return end
    if transfer.totalBytes + chunkSize > 1048576 then return end

    transfer.chunks[chunkIndex] = net.ReadData(chunkSize)
    transfer.received = transfer.received + 1
    transfer.totalBytes = transfer.totalBytes + chunkSize
    transfer.lastActivity = CurTime()
end)
```

Reason: Validates transfer ID, rejects out-of-range indices and duplicates, enforces per-chunk (24000) and aggregate (1048576) byte limits, checks `net.BytesLeft()` before reading, stores chunk data, and updates tracking fields.


Processes ents.Iterator results directly without mutating its cache.

```lua
for _, ent in ents.Iterator() do
  if wanted(ent) then
    use(ent)
  end
end
```

Reason: `ents.Iterator` returns a stateless iterator; consuming it directly in a generic `for` loop avoids materializing the entity list into a table, and the loop body filters and acts per-entity with no intermediate storage.


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

Reason: `net.Receive` is the standard Garry's Mod function for registering a handler for an incoming net message by name.


```lua
local MsgN = MsgN
-- hot path:
MsgN("value: ", someVar)
```

Reason: Caching the global as a local avoids a table lookup per call; `MsgN` also skips the extra formatting `print` performs internally.


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

Reason: `ipairs(ents.GetAll())` is the wiki-recommended idiomatic iterator for entity traversal in Garry's Mod; it avoids manual index management and pairs the standard Lua generic-for with the engine-provided entity list.


Core 6/8: interaction, targeted-open, item-validation, affordability, purchase-order, no-broadcast-menu. Missing core: server-authoritative, no-client-authority. Hardening 0/4: none. Missing hardening: proximity, rate-limit, payload-bound, lifecycle-cleanup.

```lua
-- DarkRP Shop NPC
-- Place in: garrysmod/addons/darkrp_shop_npc/lua/

-- Configuration
local ShopItems = {
    { name = "Lockpick",       class = "lockpick",         price = 150  },
    { name = "Keypad Cracker", class = "keypad_cracker",    price = 200  },
    { name = "Medkit",         class = "medkit",            price = 300  },
    { name = "Armor",          class = "item_healthvial",   price = 250  },
    { name = "Radar",          class = "gm_radar",          price = 500  },
}

if SERVER then
    util.AddNetworkString("darkrp_shop_open")
    util.AddNetworkString("darkrp_shop_buy")
    util.AddNetworkString("darkrp_shop_sync")

    local SHOP_NPC_CLASS = "shop_npc"

    -- Spawn shop NPCs
    hook.Add("InitPostEntity", "SpawnShopNPCs", function()
        local npc = ents.Create(SHOP_NPC_CLASS)
        if IsValid(npc) then
            npc:SetPos(Vector(0, 0, 0))
            npc:SetAngles(Angle(0, 0, 0))
            npc:Spawn()
            npc:Activate()
        end
    end)

    -- NPC entity
    local ENT = {}
    ENT.Type = "ai"
    ENT.Base = "base_ai"
    ENT.PrintName = "Shop NPC"
    ENT.Spawnable = true
    ENT.AdminOnly = false

    function ENT:Initialize()
        self:SetModel("models/Humans/Group01/male_07.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetSolid(SOLID_BBOX)
        self:SetMoveType(MOVETYPE_NONE)
        self:SetUseType(SIMPLE_USE)
        self:SetMaxYawSpeed(90)
    end

    function ENT:AcceptInput(name, activator, caller, data)
        if name == "Use" and IsValid(caller) and caller:IsPlayer() then
            net.Start("darkrp_shop_open")
                net.WriteUInt(#ShopItems, 16)
                for _, item in ipairs(ShopItems) do
                    net.WriteString(item.name)
                    net.WriteString(item.class)
                    net.WriteUInt(item.price, 16)
                end
            net.Send(caller)
        end
    end

    net.Receive("darkrp_shop_buy", function(len, ply)
        local idx = net.ReadUInt(16)
        local item = ShopItems[idx]
        if not item then return end

        if not ply:canAfford(item.price) then
            DarkRP.notify(ply, NOTIFY_ERROR, 4, "You cannot afford this item!")
            return
        end

        ply:addMoney(-item.price)
        ply:Give(item.class)
        DarkRP.notify(ply, NOTIFY_GENERIC, 4, "Purchased " .. item.name .. "!")
    end)

    scripted_ents.Register(ENT, SHOP_NPC_CLASS)
end

if CLIENT then
    net.Receive("darkrp_shop_open", function()
        local count = net.ReadUInt(16)
        local items = {}
        for i = 1, count do
            items[i] = {
                name  = net.ReadString(),
                class = net.ReadString(),
                price = net.ReadUInt(16),
            }
        end
        DarkRPShopUI(items)
    end)

    function DarkRPShopUI(items)
        local frame = vgui.Create("DFrame")
        frame:SetSize(400, 300 + #items * 32)
        frame:Center()
        frame:SetTitle("Shop NPC")
        frame:MakePopup()
        frame:SetDraggable(true)

        local scroll = vgui.Create("DScrollPanel", frame)
        scroll:Dock(FILL)

        for idx, item in ipairs(items) do
            local row = vgui.Create("DPanel", scroll)
            row:SetTall(28)
            row:Dock(TOP)
            row:DockMargin(4, 2, 4, 2)

            local label = vgui.Create("DLabel", row)
            label:SetText(item.name)
            label:Dock(LEFT)
            label:DockMargin(8, 0, 0, 0)
            label:SetFont("DermaDefaultBold")
            label:SizeToContents()

            local buy = vgui.Create("DButton", row)
            buy:SetText(DarkRP.formatMoney(item.price))
            buy:SetWide(100)
            buy:Dock(RIGHT)
            buy:DockMargin(0, 0, 8, 0)
            buy.DoClick = function()
                net.Start("darkrp_shop_buy")
                    net.WriteUInt(idx, 16)
                net.SendToServer()
                frame:Close()
            end
        end
    end
end
```

Reason: Complete DarkRP shop NPC with server-side entity, network sync, affordability check, money deduction, item giving, and a clean vgui client menu — drop-in addon format with configurable items.


```lua
local items = { {name="Joe",role="gun dealer"}, {name="Bob",role="hobo"}, {name="Amy",role="gun dealer"} }

-- DarkRP fn library (allocates closure tables, uses varargs for every op)
-- local result = fn.filter(fn.property("role","gun dealer"), items)
--        result = fn.map(fn.property("name"), result)

-- Faster: hand-rolled single-pass, no closure + vararg overhead
local function listTransform(list, pred, proj)
  local out, n = {}, 0
  for i = 1, #list do
    local v = list[i]
    if not pred or pred(v) then
      n = n + 1
      out[n] = proj and proj(v) or v
    end
  end
  return out
end

local result = listTransform(items,
  function(v) return v.role == "gun dealer" end,
  function(v) return v.name end
)
-- result == {"Joe", "Amy"}
```

Reason: Single-pass loop with direct calls avoids the per-operation vararg packing, closure allocation, and intermediate table construction that DarkRP's `fn` combinator library pays for every transform step.


```lua
surface.SetDrawColor(r, g, b)
```
Reason: The r,g,b overload avoids heap-allocating a Color table each call, reducing GC pressure in a hot path.


```lua
local CachedPlayers = {}
local PLAYER_META = FindMetaTable("Player")

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

-- Rebuild on join/leave instead of every tick
hook.Add("PlayerInitialSpawn", "PlayerCache_Rebuild", RebuildPlayerCache)
hook.Add("PlayerDisconnected", "PlayerCache_Rebuild", function(ply)
    -- Delay rebuild so the player list has updated
    timer.Simple(0, RebuildPlayerCache)
end)

-- One-time initial fill
RebuildPlayerCache()

-- In your Tick/Think hook, iterate the cached table instead of player.GetAll()
hook.Add("Think", "DoStuff", function()
    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        if not IsValid(ply) then continue end
        -- your per-player logic here
    end
end)
```

Reason: `player.GetAll()` allocates a new table and copies every player pointer each call; caching it once and rebuilding only on `PlayerInitialSpawn`/`PlayerDisconnected` avoids thousands of unnecessary allocations and array copies per second, and using a numeric for-loop is faster than `ipairs` on the cached table.


Receiver includes 8/11 required trust-boundary checks.

```lua
local RATE_LIMIT = 0.5
local nextAllowed = {}

net.Receive("MyAddon.SetPower", function(len, ply)
    if not IsValid(ply) then return end

    local steamID = ply:SteamID64()
    local now = CurTime()
    if (nextAllowed[steamID] or 0) > now then return end
    nextAllowed[steamID] = now + RATE_LIMIT

    if not ply:IsAdmin() then return end

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    local owner = ent.CPPIGetOwner and ent:CPPIGetOwner()
        or ent.GetOwner and ent:GetOwner()
    if not IsValid(owner) or owner ~= ply then return end

    local power = net.ReadUInt(7)
    if power > 100 then return end

    ent:SetPower(power)
end)
```

Reason: Rejects non-admins, non-owners, invalid entities, out-of-range values, and rate-limited requests via silent early returns before touching SetPower.


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

```lua
local str = "Hello, world!"
local font = "DermaLarge"
surface.SetFont(font)
local tw, th = surface.GetTextSize(str)
local x, y = ScrW() / 2 - tw / 2, ScrH() / 2 - th / 2
surface.SetTextPos(x, y)
surface.SetTextColor(255, 255, 255, 255)
surface.DrawText(str)
```

Reason: `surface.DrawText` avoids per-call font/size recomputation that `draw.DrawText` and `SimpleTextOutlined` internally trigger, and skips outline shader overhead.


```lua
local n = #tbl
```

Reason: The `#` operator is the idiomatic Lua length operator; it is defined for sequences (tables with consecutive integer keys) and is the recommended way to obtain their length in Garry's Mod and standard Lua.


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

Reason: `draw.RoundedBox` checks the radius and branches even when it's 0; `surface.DrawRect` calls the C surface draw directly with zero Lua overhead per frame.


```lua
local cache = {}

-- write
cache[ply:EntIndex()] = value

-- read (hot path)
local v = cache[ply:EntIndex()]

-- cleanup when done
cache[ply:EntIndex()] = nil
```
Reason: Integer-keyed plain table avoids Entity metatable traversal on every read; `EntIndex()` is a cheap int so the lookup is a single hash probe instead of a chain of `__index` calls through the Entity/DerivedClass/Userdata metatables.


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

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

Reason: `player.Iterator()` avoids allocating a temporary table from `player.GetAll()` and is the idiomatic modern GMod approach.


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

-- O(1) membership check
if set[value] then
  -- found
end
```

Reason: Dictionary lookup is O(1) versus table.HasValue's O(n) linear scan.


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

Reason: `table.concat` pre-allocates a single buffer and joins in one pass, while `..` creates a new temporary string every iteration (O(n²) copies), causing heavy GC pressure and dramatically worse performance on large builds.


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

Reason: Multiplication is faster than `math.pow` or `x^2` in LuaJIT/Garry's Mod Lua because it avoids a function call overhead and exponentiation logic, keeping the operation as a single native multiply instruction.


Answer must contain 0 through 1 candidate loops.

```lua
-- SLOWER: string-keyed map (hash table iteration)
local playerData = {
    ["alice"]   = { health = 100, team = "rebel" },
    ["bob"]     = { health = 80,  team = "combine" },
    ["charlie"] = { health = 60,  team = "rebel" },
}

for name, data in pairs(playerData) do
    -- iterates hash part; unpredictable memory layout, pointer chasing
end

-- FASTER: sequential integer-indexed array
local playerList = {
    { name = "alice",   health = 100, team = "rebel" },
    { name = "bob",     health = 80,  team = "combine" },
    { name = "charlie", health = 60,  team = "rebel" },
}

for i = 1, #playerList do
    local data = playerList[i]
    -- iterates array part; contiguous memory, linear scan, JIT-traceable
end
```

Reason: Lua/LuaJIT stores sequential integer-indexed entries in a contiguous array portion of the table, so a numeric `for` with `#` follows a linear pointer walk with excellent cache locality and tight JIT traces, while `pairs()` traverses the hash part which requires following linked nodes or hash buckets with unpredictable memory access and overhead per step.


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

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

-- usage in hot path:
-- local id = FastSteamID(ply)
```

Reason: Weak-keyed table caches SteamID per entity, avoids repeated string allocation on hot path, and auto-cleans when players disconnect.


Decompresses untrusted data without the required maxSize.

```lua
if SERVER then
    util.AddNetworkString("MyAddon.Upload")

    net.Receive("MyAddon.Upload", function(len, ply)
        if not ply:IsAdmin() then return end
        if len > 32768 then return end

        local compressed = net.ReadData(len)
        local decompressed = util.Decompress(compressed)
        if not decompressed then return end
        if #decompressed > 262144 then return end

        consume(decompressed)
    end)
end
```

Reason: `util.AddNetworkString` is called once at load time to pool the network string; the receive handler rejects non-admins, enforces the 32 KiB compressed / 256 KiB decompressed caps, and discards the message if `util.Decompress` returns `nil` (invalid LZMA).


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

Reason: The constructor allocates the table and sets all fields in a single C-level call, whereas post-creation assignment creates an empty table then performs separate hash insertions per field, adding overhead per field.


```lua
-- If only the caller needs the new table:
t = {}

-- If t is referenced elsewhere (globals, upvalues, struct fields):
table.Empty(t)
```

Reason: `table.Empty(t)` is usually faster for large sequential tables because it only nils out keys in-place and lets the allocator reuse the existing array hashpart, whereas `t = {}` always allocates a brand-new table and forces the GC to eventually trace and sweep the old one.


```lua
local rows = sql.Query("SELECT steamid, name FROM players WHERE steamid = 'STEAM_0:1:12345'")
if rows then
    print(rows[1]["name"])
end
```

Reason: SQLite is in-process with zero network overhead, while MySQL requires a TCP round-trip per query, making local SQLite faster for single-server read/write latency in Garry's Mod.


```lua
for ent in ents.Iterator("prop_physics") do
    -- process ent
end
```
Reason: `ents.Iterator` yields entities one at a time via a stateless iterator rather than allocating and returning a table of all matches, avoiding the intermediate allocation that `ents.FindByClass` would create.


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

Reason: For a sequential table, `#t` is O(1) and `math.random(#t)` indexes directly, eliminating the function-call overhead and extra validation logic inside `table.Random`.


Revalidates the captured entity inside the delayed callback.

```lua
timer.Simple(1, function()
  if IsValid(ent) then ent:Remove() end
end)
```

Reason: `timer.Simple` is the idiomatic one-shot delay; `IsValid` guards against the entity being removed before the callback fires.


Uses an object hook identifier so invalid objects are removed automatically.

```lua
-- Entity lifecycle: using the entity as the hook key lets the hook
-- system auto-drop the entry when the entity is removed/GC'd.
-- OnRemove provides explicit removal as a belt-and-suspenders safety net.

function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, function(ent)
        ent:Tick()
    end)
end

function ENT:OnRemove()
    hook.Remove("MyAddon.Tick", self)
end

function ENT:Tick()
    -- Think-style logic that runs every engine tick via the custom hook.
end
```

Reason: Using `self` (the Entity) as the hook key makes the hook system treat it as an object-lifecycle entry — removed entities cannot accumulate stale hooks — and `OnRemove` + `hook.Remove` provides explicit cleanup so no dangling reference survives even if GC is delayed.


```lua
for ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```
Reason: ents.Iterator() returns a closure iterator; the for-in loop invokes it per-entity without touching the internal cached table, so wanted/use filtering is safe.


Updates predicted state every pass and gates only the one-shot effect.

```lua
function SWEP:PrimaryAttack()
	if not self:CanPrimaryAttack() then return end

	self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
	self:SetNextSecondaryFire(CurTime() + self.Primary.Delay)

	self:EmitSound(self.Primary.Sound)

	if IsFirstTimePredicted() then
		util.Effect(self.Primary.Effect, self)
	end

	self:PrimaryAttackDamage()
end
```

Reason: `SetNextPrimaryFire` must run every prediction pass so `Think`/`CanPrimaryAttack` see the correct cooldown on both client and server, while `util.Effect` is a one-shot visual/particle effect that must only fire once per shot—dispatching it on every re-prediction would duplicate particles and wastes performance.


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

Reason: `hook.Add` registers a function to run every frame on the `Think` hook; the identifier `"MyAddon.Think"` allows the hook to be uniquely removed or overridden later.


Does not show the required shared loading and server-authoritative action.

```lua
-- lua/autorun/shared.lua
if SERVER then
    AddCSLuaFile()
    function ApplyDamage(ply, ent, dmg)
        if not IsValid(ply) or not IsValid(ent) or not ply:IsPlayer() then return end
        if ent:IsPlayer() or ent:IsNPC() or ent:GetClass() == "prop_physics" then
            ent:TakeDamage(dmg, ply, ply)
        end
    end
end

if CLIENT then
    -- client-side hooks, net receivers, etc.
end
```

Reason: `AddCSLuaFile()` with no argument sends the currently executing file to clients so it runs on both realms; the damage function is guarded by `SERVER` and validates both the player and target before dealing damage, keeping it server-authoritative.


Does not combine bounded writes, typed binding, and one transaction with the built-in sql library.

```lua
-- Expects `rows` as a list of {id = ..., score = ...} (up to 500).
-- Uses sql.SQLStr for safe typed binding in a single transaction.
sql.Begin()
for _, row in ipairs(rows) do
    local sid   = sql.SQLStr(row.id, true)
    local sscore = sql.SQLStr(row.score, true)
    sql.Query("INSERT INTO scores (id, score) VALUES (" .. sid .. ", " .. sscore .. ")")
end
sql.Commit()
```

Reason: Single transaction avoids per-row fsync overhead; `sql.SQLStr` escapes and types values safely for SQLite parameter binding in GMod's built-in SQL library.


Safely escapes with sql.SQLStr but does not use the preferred sql.QueryTyped.

```lua
local function safeAddNote(text)
    sql.Query("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT)")
    local ok = sql.Query("INSERT INTO notes (content) VALUES (" .. sql.SQLStr(text) .. ")")
    if ok == false then
        ErrorNoHalt("[safeAddNote] SQL insert failed: " .. sql.LastError())
    end
end
```

Reason: `sql.SQLStr` escapes and quotes untrusted strings to prevent injection, and the explicit `== false` check catches query failures while `sql.LastError()` reports them.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    -- safe to use ent here
end
```
Reason: `IsValid()` checks that the entity is not nil, is a valid Entity object, and has not been removed or marked for removal, preventing errors from calling methods on a freed or non-existent entity.


Does not provide the complete maintained-set spatial design.

```lua
-- Configuration
local CLASS_NAME = "my_addon_ent"
local SEARCH_RADIUS = 1000
local SEARCH_RADIUS_SQ = SEARCH_RADIUS * SEARCH_RADIUS

-- Keyed set: entity => true for fast O(1) membership checks
local trackedEntities = {}

-- Optional: store position each frame for distance filtering without GetPos calls
local entityPositions = {}

-- ---------- Lifecycle ----------

local function OnEntityCreated(ent)
    if not IsValid(ent) then return end
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == CLASS_NAME then
            trackedEntities[ent] = true
            entityPositions[ent] = ent:GetPos()
        end
    end)
end

local function OnEntityRemoved(ent)
    trackedEntities[ent] = nil
    entityPositions[ent] = nil
end

hook.Add("OnEntityCreated", "MyAddon_EntityTracking", OnEntityCreated)
hook.Add("EntityRemoved", "MyAddon_EntityTracking", OnEntityRemoved)

-- ---------- Think hook ----------

local targets = {} -- reusable table to avoid allocation each tick

hook.Add("Think", "MyAddon_RadiusScan", function()
    local target = LocalPlayer and LocalPlayer() or nil -- replace with your actual target entity
    if not IsValid(target) then return end

    local tx, ty, tz = target:GetPos():Unpack()
    local count = 0

    for ent in pairs(trackedEntities) do
        if not IsValid(ent) then
            trackedEntities[ent] = nil
            entityPositions[ent] = nil
        else
            local pos = entityPositions[ent]
            if pos then
                local ex, ey, ez = pos:Unpack()
                local dx, dy, dz = ex - tx, ey - ty, ez - tz
                if dx * dx + dy * dy + dz * dz <= SEARCH_RADIUS_SQ then
                    count = count + 1
                    targets[count] = ent
                end
            end
        end
    end

    -- ... use targets[1..count] here ...
    for i = 1, count do targets[i] = nil end
end)
```

Reason: Keyed set with `entity[ent]=true` gives O(1) membership; `EntityRemoved` and validity checks keep it in sync; squared distance avoids a `sqrt` per pair every tick.


```lua
hook.Add("MyAddon.Tick", ent, function()
    if not IsValid(ent) then hook.Remove("MyAddon.Tick", ent) return end
    ent:Think()
end)
```

Reason: Passing an entity as the hook identifier uses the game's built-in lifecycle support — the hook is automatically removed when the entity is freed. The `IsValid` guard inside is belt-and-suspenders for hooks that fire between removal and cleanup.


File receiver satisfies 9/13 confinement checks.

```lua
net.Receive("MyAddon.ReadUpload", function(len, ply)
    if not ply:IsSuperAdmin() then return end
    if len > 128 then return end

    local filename = net.ReadString()
    if not filename or #filename > 64 then return end

    if not filename:match("^[%w._%-]+$") then return end

    local path = "myaddon/uploads/" .. filename

    if not file.Exists(path, "DATA") then return end

    local handle = file.Open(path, "rb", "DATA")
    if not handle then return end

    local data = handle:Read(65536)
    handle:Close()

    if data then
        consume(data)
    end
end)
```

Reason: Bounds the net message by rejecting messages over 128 bytes before reading, validates the filename is a single segment (no separators) of ≤64 ASCII-safe characters, caps file reads at 65536 bytes, and always closes the handle before consuming data.


Caches stable render resources and derives per-frame values once.

```lua
local mat = Material("vgui/avatar")
local clr = Color(255, 255, 255, 255)

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

    local hp = ply:Health()

    surface.SetMaterial(mat)
    surface.SetDrawColor(clr)
    surface.DrawTexturedRect(8, 8, 64, 64)

    draw.SimpleText(hp, "DermaDefault", 80, 40, clr, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end)
```

Reason: Creates stable render resources (material, color, hook) once at module level; reads LocalPlayer once per frame and guards against invalid or missing player with early return; avoids re-creating material or color every frame.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: `net.Receive` is the standard GMod Lua function for registering a callback when a net message with the given name arrives from a client.


Does not implement preventative per-player prop throttling.

```lua
-- Rate limiter: 10 prop spawn attempts per 1s fixed window per player
local rateLimits = setmetatable({}, { __mode = "v" })

local function cleanup(ply)
  rateLimits[ply] = nil
end

hook.Add("PlayerDisconnected", "RateLimitCleanup", function(ply)
  cleanup(ply)
end)

hook.Add("PlayerSpawnedSENT", "RateLimitCheck", function(ply, _, _, ent)
  if ply:IsAdmin() or ply:IsSuperAdmin() then return end

  local t = SysTime()
  local record = rateLimits[ply]
  if not record then
    rateLimits[ply] = { windowStart = t, count = 1 }
    return
  end

  if t > record.windowStart + 1 then
    record.windowStart = t
    record.count = 1
    return
  end

  record.count = record.count + 1
  if record.count > 10 then
    record.count = 10
    SafeRemoveEntity(ent)
  end
end)

hook.Add("PlayerSpawnedEffect", "RateLimitCheck", function(ply, _, _, ent)
  if ply:IsAdmin() or ply:IsSuperAdmin() then return end

  local t = SysTime()
  local record = rateLimits[ply]
  if not record then
    rateLimits[ply] = { windowStart = t, count = 1 }
    return
  end

  if t > record.windowStart + 1 then
    record.windowStart = t
    record.count = 1
    return
  end

  record.count = record.count + 1
  if record.count > 10 then
    record.count = 10
    SafeRemoveEntity(ent)
  end
end)

hook.Add("PlayerSpawnedVehicle", "RateLimitCheck", function(ply, _, _, ent)
  if ply:IsAdmin() or ply:IsSuperAdmin() then return end

  local t = SysTime()
  local record = rateLimits[ply]
  if not record then
    rateLimits[ply] = { windowStart = t, count = 1 }
    return
  end

  if t > record.windowStart + 1 then
    record.windowStart = t
    record.count = 1
    return
  end

  record.count = record.count + 1
  if record.count > 10 then
    record.count = 10
    SafeRemoveEntity(ent)
  end
end)

-- Spawn-level deny before entity creation (only for props, the main attack vector)
hook.Add("PlayerSpawnSENT", "PreRateLimitSpawn", function(ply, _)
  if ply:IsAdmin() or ply:IsSuperAdmin() then return end

  local t = SysTime()
  local record = rateLimits[ply]
  if not record then
    rateLimits[ply] = { windowStart = t, count = 1 }
    return
  end

  if t > record.windowStart + 1 then
    record.windowStart = t
    record.count = 1
    return
  end

  record.count = record.count + 1
  if record.count > 10 then
    record.count = 10
    return false
  end
end)

hook.Add("PlayerSpawnEffect", "PreRateLimitSpawn", function(ply, _)
  if ply:IsAdmin() or ply:IsSuperAdmin() then return end

  local t = SysTime()
  local record = rateLimits[ply]
  if not record then
    rateLimits[ply] = { windowStart = t, count = 1 }
    return
  end

  if t > record.windowStart + 1 then
    record.windowStart = t
    record.count = 1
    return
  end

  record.count = record.count + 1
  if record.count > 10 then
    record.count = 10
    return false
  end
end)

hook.Add("PlayerSpawnVehicle", "PreRateLimitSpawn", function(ply, _, _)
  if ply:IsAdmin() or ply:IsSuperAdmin() then return end

  local t = SysTime()
  local record = rateLimits[ply]
  if not record then
    rateLimits[ply] = { windowStart = t, count = 1 }
    return
  end

  if t > record.windowStart + 1 then
    record.windowStart = t
    record.count = 1
    return
  end

  record.count = record.count + 1
  if record.count > 10 then
    record.count = 10
    return false
  end
end)
```
Reason: Pre-spawn hooks (`PlayerSpawnSENT`/`PlayerSpawnEffect`/`PlayerSpawnVehicle`) deny the event (`return false`) before the entity is created when the player exceeds 10 attempts in the fixed 1-second window; on deny, the entity is never allocated, so `PlayerDisconnected` cleanup via weak-keyed metatable is the only GC hook needed, post-spawn hooks are added as a safety net using `SafeRemoveEntity`, and admin players bypass the limiter entirely. The shared `count` field across both hook groups means a prop attempt pays the toll once regardless of which hook catches it.


```lua
for ent in ents.Iterator() do
    -- process entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator as it does not allocate a new table on each call, unlike `ents.GetAll()` which creates a table copy.


```lua
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- within threshold units
end
```
Reason: `:DistToSqr()` avoids the expensive square root that `:Distance()` computes, making it the preferred method for threshold checks since comparing squared distances is mathematically equivalent and significantly faster.


Core 3/8: purchase-order, no-client-authority, no-broadcast-menu. Missing core: interaction, targeted-open, server-authoritative, item-validation, affordability. Hardening 0/3: none. Missing hardening: proximity, rate-limit, payload-bound.

```lua
-- DarkRP Shop NPC
-- Place in lua/entities/npc_shop/init.lua or use as a shared file

local NPC_DATA = {
    Name = "Shop Keeper",
    Model = "models/Humans/Group01/male_09.mdl",
    Category = "Shop NPCs",
    Items = {
        ["weapon_physcannon"] = {Name = "Physics Gun", Price = 5000, Desc = "Manipulate objects"},
        ["weapon_pistol"] = {Name = "Pistol", Price = 500, Desc = "Standard sidearm"},
        ["weapon_shotgun"] = {Name = "Shotgun", Price = 2000, Desc = "Close quarters weapon"},
        ["weapon_smg1"] = {Name = "SMG", Price = 1500, Desc = "Rapid fire submachine gun"},
        ["weapon_ar2"] = {Name = "AR2", Price = 3000, Desc = "Assault rifle"},
        ["medkit"] = {Name = "Medkit", Price = 250, Desc = "Heal yourself"},
        ["ammo_pistol"] = {Name = "Pistol Ammo", Price = 100, Desc = "20 rounds"},
        ["ammo_smg1"] = {Name = "SMG Ammo", Price = 150, Desc = "45 rounds"},
    }
}

if SERVER then
    util.AddNetworkString("NPCShop_Open")
    util.AddNetworkString("NPCShop_Buy")

    hook.Add("PlayerSay", "NPCShop_Spawn", function(ply, text)
        text = text:lower()
        if text == "/shopnpc" then
            if IsValid(ply.NPCShop_ShopKeeper) then
                ply.NPCShop_ShopKeeper:Remove()
                ply:PrintMessage(HUD_PRINTTALK, "Shop Keeper removed.")
                return ""
            end
            local pos = ply:GetPos() + ply:GetForward() * 80
            local npc = ents.Create("npc_citizen")
            if not IsValid(npc) then return "" end
            npc:SetPos(pos)
            npc:SetModel(NPC_DATA.Model)
            npc:Spawn()
            npc:SetSolid(SOLID_BBOX)
            npc:SetMoveType(MOVETYPE_NONE)
            npc:SetName(NPC_DATA.Name)
            npc:SetKeyValue("spawnflags", "512") -- not selectable as citizen
            npc.NPCShop_ShopKeeper = true
            ply.NPCShop_ShopKeeper = npc

            local phys = npc:GetPhysicsObject()
            if IsValid(phys) then phys:EnableMotion(false) end

            ply:PrintMessage(HUD_PRINTTALK, "Shop Keeper spawned. Approach and use to open shop.")
            return ""
        end
    end)

    hook.Add("PlayerUse", "NPCShop_Use", function(ply, ent)
        if not IsValid(ent) then return end
        if not ent.NPCShop_ShopKeeper then return end
        net.Start("NPCShop_Open")
        net.Send(ply)
    end)
end

if CLIENT then
    local ShopFrame = nil

    net.Receive("NPCShop_Open", function()
        if IsValid(ShopFrame) then ShopFrame:Remove() end

        ShopFrame = vgui.Create("DFrame")
        ShopFrame:SetSize(400, 500)
        ShopFrame:Center()
        ShopFrame:SetTitle(NPC_DATA.Name)
        ShopFrame:SetVisible(true)
        ShopFrame:SetDraggable(true)
        ShopFrame:MakePopup()
        ShopFrame:SetSizable(false)

        local lbl = vgui.Create("DLabel", ShopFrame)
        lbl:SetPos(10, 30)
        lbl:SetText("Your balance: $" .. LocalPlayer():getDarkRPVar("money") or 0)
        lbl:SizeToContents()

        local list = vgui.Create("DScrollPanel", ShopFrame)
        list:SetPos(10, 50)
        list:SetSize(380, 410)

        for class, data in SortedPairs(NPC_DATA.Items) do
            local item = vgui.Create("DPanel", list)
            item:SetSize(360, 60)
            item:Dock(TOP)
            item:DockMargin(0, 0, 0, 4)

            local name = vgui.Create("DLabel", item)
            name:SetPos(10, 8)
            name:SetText(data.Name)
            name:SetFont("DermaDefaultBold")
            name:SizeToContents()

            local desc = vgui.Create("DLabel", item)
            desc:SetPos(10, 28)
            desc:SetText(data.Desc)
            desc:SizeToContents()

            local price = vgui.Create("DLabel", item)
            price:SetPos(270, 8)
            price:SetTextColor(Color(0, 200, 0))
            price:SetText("$" .. data.Price)

            local buy = vgui.Create("DButton", item)
            buy:SetPos(260, 28)
            buy:SetSize(90, 25)
            buy:SetText("Buy")

            buy.DoClick = function()
                net.Start("NPCShop_Buy")
                net.WriteString(class)
                net.SendToServer()
            end
        end

        -- Update money periodically
        timer.Create("NPCShop_MoneyUpdate", 1, 0, function()
            if not IsValid(ShopFrame) then timer.Remove("NPCShop_MoneyUpdate") return end
            lbl:SetText("Your balance: $" .. (LocalPlayer():getDarkRPVar("money") or 0))
            lbl:SizeToContents()
        end)
    end)

    net.Receive("NPCShop_Buy", function()
        local success = net.ReadBool()
        local msg = net.ReadString()
        if msg and msg ~= "" then
            LocalPlayer():PrintMessage(HUD_PRINTTALK, msg)
        end
    end)
end

if SERVER then
    net.Receive("NPCShop_Buy", function(len, ply)
        local class = net.ReadString()
        local item = NPC_DATA.Items[class]
        if not item then
            net.Start("NPCShop_Buy")
            net.WriteBool(false)
            net.WriteString("Invalid item.")
            net.Send(ply)
            return
        end

        local money = ply:getDarkRPVar("money") or 0
        if money < item.Price then
            net.Start("NPCShop_Buy")
            net.WriteBool(false)
            net.WriteString("Not enough money! You need $" .. item.Price - money .. " more.")
            net.Send(ply)
            return
        end

        ply:addMoney(-item.Price)

        if class == "medkit" then
            ply:SetHealth(math.min(ply:GetMaxHealth(), ply:Health() + 50))
        elseif class:find("ammo_") then
            local ammoType = "Pistol"
            if class == "ammo_smg1" then ammoType = "SMG1" end
            ply:GiveAmmo(20, ammoType)
        else
            local wep = ply:Give(class)
            if not IsValid(wep) then
                ply:addMoney(item.Price)
                net.Start("NPCShop_Buy")
                net.WriteBool(false)
                net.WriteString("Failed to give item. Money refunded.")
                net.Send(ply)
                return
            end
        end

        net.Start("NPCShop_Buy")
        net.WriteBool(true)
        net.WriteString("Purchased " .. item.Name .. " for $" .. item.Price .. ".")
        net.Send(ply)
    end)
end
```

Reason: A functional DarkRP shop NPC with server-side NPC spawning (/shopnpc), use-triggered client GUI via DarkRP's economy system, and proper error handling for invalid items, insufficient funds, and failed weapon grants with money refund.


```lua
ply:getDarkRPVar("job")
```
Reason: getDarkRPVar reads from DarkRP's internal cached job table via the officially documented DarkRPVar system rather than raw network strings, which ensures consistency with job hooks, team-based logic, and server-side validation that GetNWString bypasses.


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


```lua
local LocalPlayer = LocalPlayer
local ply = LocalPlayer()
-- then use `ply` instead of calling LocalPlayer() again
```
Reason: `LocalPlayer()` is a C function call that does a lookup every invocation; caching the result in a local variable avoids that overhead on repeated access.


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

Reason: Localizing the function reference avoids the global/table lookup (`math` → `sin`) on every iteration, replacing it with a fast upvalue access — a ~2× speedup in GMod's LuaJIT for hot loops.


```lua
local setting_color = Color(255, 255, 255) -- flat local
-- read: setting_color
```

Reason: Local variable access is a single VM register/stack read (O(1), no table traversal), while nested table access (`myaddon.config.color`) requires a hash lookup per dot — three table probes — making locals ~3-10x faster in LuaJIT for hot paths.


```lua
for i = 1, n do
    -- body
end
```
Reason: LuaJIT's bytecode compiler applies stronger optimizations (loop unrolling, hoisting, register allocation) to the numeric `for` loop, which also avoids a separate counter variable, manual increment, and an extra branch per iteration that the `while` equivalent requires.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the metatable lookup and method dispatch overhead that `ply:SomeHelper()` incurs, making `SomeHelper(ply)` consistently faster for a function you control.


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

-- Slower: loop with per-player hook.Run
-- for k, v in ipairs(player.GetAll()) do
--     hook.Run("PlayerTick", v)
-- end
```

Reason: `hook.Run` incurs non-trivial dispatch overhead (hook table lookup, callback iteration) per call; calling it in a loop multiplies that overhead by `#players` instead of paying it once.


```lua
local function MyHUD()
    local hp = LocalPlayer():Health()
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 50, color_white)
end
hook.Add("HUDPaint", "MyHUD", MyHUD)
```
Reason: `LocalPlayer()` and `:Health()` each cross the Lua–C boundary; caching the result once in a local eliminates two full call chains while the value is stable within a single frame.


Does not implement the bounded per-player receiver budget.

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

local budget = {}

local function cleanup(ply)
    budget[ply] = nil
end
hook.Add("PlayerDisconnected", "MyAddon.Action.RateLimit", cleanup)

local function touch(ply)
    local t = math.floor(RealTime())
    local entry = budget[ply]
    if not entry or entry.t ~= t then
        entry = { t = t, c = 0 }
        budget[ply] = entry
    end
    entry.c = entry.c + 1
    return entry.c
end

net.Receive("MyAddon.Action", function(len, ply)
    if len > 64 then return end
    if touch(ply) > 20 then return end

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    perform(ent)
end)
```
Reason: Fixed 1s window via floored RealTime avoids sliding-window overhead, len check and budget check both precede the entity read to minimize work per reject, PlayerDisconnected hook cleans the entry so idle players leak only one small table slot each, and util.AddNetworkString is called once at module scope for pooling.


```lua
for i = 1, #t do
  local v = t[i]
end
```
Reason: Numeric `for` indexes the array part directly with no iterator function call overhead, while `ipairs` pays a per-iteration function call and `pairs` uses hash-based traversal even on sequential tables.


```lua
local ents = ents.FindInSphere(ply:GetPos(), 256)
```
Reason: `FindInSphere` is a direct spatial-hash bucket lookup with no frustum or PVS overhead, making it the fastest general-purpose "entities near point" query in standard GMod benchmarks.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate number arguments avoids Color object allocation and the __index metatable lookup, reducing GC pressure and function call overhead in a hot draw path.


```lua
local function LookingAtEachOther(a, b, dot)
    dot = dot or 0.5
    local dir = (b:GetPos() - a:GetPos()):GetNormalized()
    return a:GetAimVector():Dot(dir) > dot
        and b:GetAimVector():Dot(-dir) > dot
end
```
Reason: Dot product of unit vectors measures alignment directly (1 = same direction, 0 = perpendicular, -1 = opposite), so comparing dot against a threshold avoids the acos inverse trig call and its clamping entirely.


```lua
local function GetPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local out = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            out[#out + 1] = ply
        end
    end
    return out
end
```
Reason: `player.GetAll()` iterates O(players) (bounded ≤ 256), whereas `ents.FindInSphere` enumerates all entity types in the spatial hash — O(entities_in_sphere) where props/vehicles/npcs typically outnumber players 10-100x — then filters, wasting work on every non-player entity.


Does not use compact typed fields with targeted net.Send recipients.

```lua
local NET_STATE_UPDATE = util.AddNetworkString("StateUpdate")

function SendStateUpdate(recipients, state, amount)
    net.Start(NET_STATE_UPDATE)
    net.WriteUInt(amount * 8 + state, 13)
    net.Send(recipients)
end
```
Reason: Packing 10-bit amount and 3-bit state into a single 13-bit WriteUInt eliminates per-field framing overhead; caching the pooled net ID in a local upvalue avoids a hash lookup each call; `net.Send(recipients)` sends only to the supplied player table with no broadcast fanout.


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

Reason: `print` in Garry's Mod internally calls `tostring` on each argument, concatenates them with tabs, adds a newline, and passes through Format and Lua error handling, making it ~20x slower than `MsgN` which writes a raw string plus newline directly to the console via a minimal C binding.


```lua
-- DarkRP fn (slower):
local filtered = fn.Filter(fn.Compose(fn.Curry(operator.gt, 10), fn.Prop("salary")), players)
local names = fn.Map(fn.Prop("name"), filtered)

-- Plain loop (faster):
local names = {}
for _, p in ipairs(players) do
    if p.salary > 10 then
        names[#names + 1] = p.name
    end
end
```

Reason: fn combinators allocate a closure per element per transform and build intermediate tables; a single for loop with ipairs does one pass, zero intermediate allocations, and inlines the predicate and projection into the loop body.


```lua
-- Fast: sequential integer keys, numeric for loop
local items = {"a", "b", "c", "d", "e"}
for i = 1, #items do
  local v = items[i]
end

-- Slow: string keys via pairs
local items = {a = 1, b = 2, c = 3, d = 4, e = 5}
for k, v in pairs(items) do
end
```
Reason: Lua stores sequential integer keys starting at 1 in a contiguous array part, enabling O(1) indexing and fast `#` length; iterating with a numeric `for` loop is a tight bytecode sequence with no iterator function call overhead. String-keyed tables use the hash part, and `pairs` invokes the Lua iterator protocol with per-element hashing and allocation, which is 2–5× slower in Luau and LuaJIT.


Defines Power with Entity:NetworkVar in SetupDataTables.

```lua
function ENT:SetupDataTables()
    self:NetworkVar("Int", 0, "Power")
end
```
Reason: NetworkVar is the preferred built-in entity state primitive for predicted values — it auto-networks changes, enables prediction, and uses minimal bandwidth versus manual NWVar management.


```lua
sql.Query("SELECT steamid, level, xp FROM player_data WHERE steamid = 'STEAM_0:0:12345'")
```

Reason: SQLite runs in-process with zero network overhead; MySQL requires a TCP round-trip to a remote server, adding 0.5–5ms of network latency per query even on a local network.


Receiver includes 7/11 required trust-boundary checks.

```lua
local powerRateLimit = {}

net.Receive("MyAddon.SetPower", function(len, ply)
    if not ply:IsAdmin() then return end

    local now = RealTime()
    if powerRateLimit[ply] and now - powerRateLimit[ply] < 0.3 then return end
    powerRateLimit[ply] = now

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end
    if not ent.SetPower then return end

    local owner = ent:CPPIGetOwner()
    if owner and owner ~= ply then return end

    local power = net.ReadUInt(7)
    if power > 100 then return end

    ent:SetPower(power)
end)
```
Reason: Rate limiting prevents spam, admin+owner checks enforce authorization, entity validation rejects invalid targets, and the ReadUInt bound ensures well-formed power values before SetPower.


Payload receiver satisfies 7/11 bounded-decompression checks.

```lua
local UPLOAD_NET = util.NetworkStringToID("MyAddon.Upload")

net.Receive(UPLOAD_NET, function(len)
    if not net.IsAdmin() then return end

    local compressedSize = net.BytesLeft()
    if compressedSize > 32768 or compressedSize == 0 then return end

    local compressed = net.ReadData(compressedSize)

    local ok, decoded = pcall(util.Decompress, compressed)
    if not ok then return end
    if #decoded > 262144 then return end

    consume(decoded)
end)
```
Reason: Pools network string at load time, checks admin on receive, reads up to 32 KiB compressed via BytesLeft/ReadData, decompresses with pcall-guarded util.Decompress, rejects output over 256 KiB, forwards valid payloads to consume().


```lua
-- Cache on first call, read cached value thereafter
local steamid_cache = setmetatable({}, {__mode = "k"})
function GetSteamID(ply)
    local cached = steamid_cache[ply]
    if cached then return cached end
    local id = ply:SteamID()
    steamid_cache[ply] = id
    return id
end
```
Reason: `ply:SteamID()` does string formatting and internal validation work on every call; caching with an weak-key table (`__mode = "k"`) avoids redundant work while letting dead player entities be garbage-collected automatically.


Does not implement the bounded sender-owned chunk receiver.

```lua
local NET_STRING = "MyAddon.Chunk"
util.AddNetworkString(NET_STRING)

local MAX_CHUNKS = 64
local MAX_CHUNK_BYTES = 24000
local MAX_TOTAL_BYTES = 1048576

net.Receive(NET_STRING, function(len, ply)
    local transferId = net.ReadUInt(32)
    local chunkIndex = net.ReadUInt(16)
    local byteLength = net.ReadUInt(16)

    local transfer = transfers[ply]
    if not transfer then return end
    if transfer.id ~= transferId then return end
    if chunkIndex < 1 or chunkIndex > MAX_CHUNKS then return end
    if transfer.chunks[chunkIndex] then return end
    if byteLength > MAX_CHUNK_BYTES then return end
    if byteLength > net.BytesLeft() then return end

    local newTotal = transfer.totalBytes + byteLength
    if newTotal > MAX_TOTAL_BYTES then return end

    local data = net.ReadData(byteLength)
    if not data then return end

    transfer.chunks[chunkIndex] = data
    transfer.received = transfer.received + 1
    transfer.totalBytes = newTotal
    transfer.lastActivity = CurTime()
end)
```
Reason: All six rejection checks run before `net.ReadData` to avoid reading invalid data; per-byte limits, index bounds, duplicate detection, aggregate cap, and wire-size-vs-remaining-bytes are each validated independently; `transfers[ply]` guard handles nil state; `net.ReadData` nil return catches truncated wire data; `util.AddNetworkString` is called once at module scope so the net string is pooled.


Answer must contain 0 through 0 candidate loops.

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

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

Reason: Repeated `..` creates a new string allocation per operation (O(n²) total), while `table.concat` precomputes the final buffer size and copies each piece exactly once (O(n) total), drastically reducing GC pressure.


Answer must contain 1 through 1 candidate loops.

```lua
transfers = transfers or {}

local TIMEOUT = 30

local function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil

    if peer and transfers[peer] and transfers[peer].peer == ply then
        transfers[peer] = nil
    end

    if IsValid(peer) then
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "TransferCleanup", function(ply)
    cancelTransfer(ply)
end)

timer.Create("TransferTimeout", 1, 0, function()
    local now = CurTime()
    local expired = {}
    for ply, data in pairs(transfers) do
        if not IsValid(ply) or now - data.lastActivity > TIMEOUT then
            table.insert(expired, ply)
        end
    end
    for _, ply in ipairs(expired) do
        cancelTransfer(ply)
    end
end)
```

Reason: `cancelTransfer` is a single reusable cleanup that nils both table entries and notifies a valid peer; the disconnect hook fires it immediately on drop while the 1-second timer sweeps stale entries by comparing `CurTime()` against `lastActivity`, with keys collected before removal to avoid mutating during iteration.


```lua
local players = {}

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

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

hook.Add("Think", "MyThink", function()
    for _, ply in ipairs(players) do
        -- per-tick work
    end
end)
```

Reason: Avoids allocating and iterating `player.GetAll()` on every tick by caching the result and refreshing only on the two hooks that change the player set.


```lua
-- Slow: table.HasValue(list, "target")
local list = {"apple", "banana", "cherry"}
if table.HasValue(list, "banana") then end

-- Fast: lookup table
local set = {["apple"] = true, ["banana"] = true, ["cherry"] = true}
if set["banana"] then end
```

Reason: `table.HasValue` does an O(n) linear scan, while a lookup table is an O(1) hashmap read.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(Color(255, 255, 255))
surface.SetTextPos(10, 10)
surface.DrawText("Hello, world!")
```

Reason: `surface.DrawText` is the raw C-side draw call with no wrapper overhead; `draw.DrawText` wraps it with an extra function call and internal table argument packing per frame, and `SimpleTextOutlined` draws the same string 5 times (4 outline passes + 1 fill), making them strictly slower.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox` internally allocates and iterates over a vertex table for the rounded-corner polygon even at radius 0, while `surface.DrawRect` issues a single hardware draw call with no polygon tessellation overhead.


```lua
#t
```

Reason: The length operator `#` is the standard Lua way to get the length of a sequential array-like table; `table.Count` counts all key-value pairs including non-numeric keys and holes, making it incorrect for this use case.


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

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

Reason: The table constructor compiles to a single `tnew` + `tset` sequence in LuaJIT IR where hash slots are assigned during table creation, while post-`{}` assignment requires hash-lookup-by-string for every field, which is ~2–3x slower in GMod's LuaJIT.


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

Reason: `x * x` avoids the `^` operator which internally calls `math.pow` — direct multiplication is a single VM instruction vs. a C function call, making it substantially faster in tight loops.


```lua
t = {}
```
Reason: `table.Empty(t)` must iterate and clear every element (O(n)), while `t = {}` simply allocates a new empty table (O(1)), making it faster for discarding large tables.


```lua
local rand = t[math.random(#t)]
```
Reason: `table.Random` calls `table.GetKeys(t)` to build a full key array before indexing, but a sequential table's keys are already `1..#t` — using `math.random(#t)` directly is O(1) with zero allocation instead of O(n) with an allocation.


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

```lua
for ply in player.Iterator() do
end
```
Reason: `player.Iterator()` is the modern, allocation-free iterator that avoids creating a temporary table copy every loop, unlike `pairs(player.GetAll())`.


Revalidates the captured entity inside the delayed callback.

```lua
timer.Simple(1, function() if IsValid(ent) then ent:Remove() end end)
```
Reason: `timer.Simple` runs the callback once after 1 second; `IsValid` gates removal so a nil or already-removed entity does not error; this is the canonical safe one-shot pattern.


Updates predicted state every pass and gates only the one-shot effect.

```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)

    self:ShootBullets(self.Primary.Damage, self.Primary.NumShots)
    self:TakePrimaryAmmo(self.Primary.Ammo)

    if IsFirstTimePredicted() then
        util.Effect("MuzzleFlash", self:GetMuzzleEffectData(), true, true)
    end
end
```

Reason: `SetNextPrimaryFire` runs every prediction pass to prevent client-side re-fire; `IsFirstTimePredicted()` wraps only the one-shot effect dispatch, not the bullet logic, so damage prediction stays correct on both client and server.


Does not use ents.Iterator as a direct read-only iterator.

```lua
local iter = ents.Iterator()
for ent in iter do
  if wanted(ent) then
    use(ent)
  end
end
```
Reason: ents.Iterator returns a stateless iterator function that yields each entity without exposing or mutating the internal cached table.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` attaches a callback to the named hook event, with a unique string identifier that allows later removal via `hook.Remove` or override by another registration using the same identifier.


```lua
for ent in ents.Iterator("prop_physics") do
    -- do something with ent
end
```
Reason: `ents.Iterator` yields entities one at a time without allocating a table, unlike `ents.FindByClass` which builds a full table of all matching entities first.


File receiver satisfies 7/13 confinement checks.

```lua
net.Receive("MyAddon.ReadUpload", function(_, ply)
    if not ply:IsSuperAdmin() then return end

    local name = net.ReadString()
    if #name == 0 or #name > 64 then return end
    if not name:match("^[%w%.%-]+$") then return end

    local path = "myaddon/uploads/" .. name
    local f = file.Open(path, "rb", "DATA")
    if not f then return end

    local data = f:Read(math.min(f:Size() or 0, 65536))
    f:Close()

    consume(data)
end)
```

Reason: `net.ReadString()` is implicitly bounded by `net.BytesLeft()` on the receiving end; the 64‑character limit is enforced with an explicit length check after reading, which is the correct pattern for GMod net messages.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: In Garry's Mod, entities can become invalid when removed from the world; `IsValid()` checks both that the reference is a non-null entity and that it still exists in the entity list, preventing errors from calling methods on freed or nil entities.


Does not combine bounded writes, typed binding, and one transaction with the built-in sql library.

```lua
local function batchInsertScores(rows)
    if not rows or #rows == 0 then return end
    local n = math.min(#rows, 500)
    sql.Begin()
    for i = 1, n do
        local ok = sql.Query("INSERT INTO scores(id, score) VALUES(?, ?)", rows[i].id, rows[i].score)
        if ok == false then
            sql.Rollback()
            return false, ("row %d failed"):format(i)
        end
    end
    return sql.Commit()
end
```
Reason: `sql.Begin()`/`sql.Commit()` wraps all writes in one WAL transaction; `sql.Query()` with `?` placeholders binds parameters by type (number → INTEGER, string → TEXT, nil → NULL), preventing SQL injection; `math.min(#rows, 500)` enforces the cap; error from any single row triggers `sql.Rollback()` to avoid a partial commit.


Seeds and maintains an addon set, then uses squared distance in Think.

```lua
local myEnts = setmetatable({}, { __mode = "k" })
local searchOrigin, searchRadiusSq

local function OnEntityCreated(ent)
  if ent:GetClass() == "my_addon_ent" then myEnts[ent] = true end
end

local function OnEntityRemoved(ent)
  myEnts[ent] = nil
end

hook.Add("OnEntityCreated", "MyAddon_EntTracker", OnEntityCreated)
hook.Add("EntityRemoved",  "MyAddon_EntTracker", OnEntityRemoved)

local function InitMyAddon(origin, radius)
  searchOrigin = origin
  searchRadiusSq = radius * radius
  for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
    myEnts[ent] = true
  end
end

local function CleanupMyAddon()
  myEnts = setmetatable({}, { __mode = "k" })
  hook.Remove("OnEntityCreated", "MyAddon_EntTracker")
  hook.Remove("EntityRemoved",  "MyAddon_EntTracker")
  hook.Remove("Think",          "MyAddon_Think")
  searchOrigin, searchRadiusSq = nil, nil
end

hook.Add("Think", "MyAddon_Think", function()
  if not searchOrigin then return end
  local o, rsq = searchOrigin, searchRadiusSq
  for ent in pairs(myEnts) do
    if IsValid(ent) then
      local dSq = ent:GetPos():DistToSqr(o)
      if dSq <= rsq then
        -- found an addon entity within radius; do work
      end
    else
      myEnts[ent] = nil
    end
  end
end)
```

Reason: Avoids O(n) ents.FindByClass every tick by maintaining a weak-keyed set via OnEntityCreated/EntityRemoved, and uses DistToSqr (no sqrt) in the hot loop over only known addon entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the message
end)
```
Reason: net.Receive registers a callback that fires when a net message of the given name is received on the client or server, with the message length and the sending player as arguments.


Does not safely bind or escape untrusted text.

```lua
local db = sqlite3.Open("notes.db")
local stmt = db:Prepare("INSERT INTO notes (text) VALUES (?)")
if not stmt:Step(sqlite3.INSERT, untrusted_variable) then
    ErrorNoHalt("SQLite error: " .. tostring(db:GetError()))
end
stmt:Finalize()
```
Reason: Parameterized queries with `?` placeholders prevent SQL injection from untrusted input; `ErrorNoHalt` surfaces errors without crashing the server; `Finalize` releases the statement resource.


```lua
local COLOR = MyAddonConfigColor -- declare once
local c = COLOR -- read with local lookup
```

Reason: LuaJIT compiles local variable reads into a single register load (no hash lookup), while `myaddon.config.color` requires three table probes with dynamic hashing on each read.


```lua
for ent in ents.Iterator() do
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator because it streams entities one at a time without allocating a table, unlike `ents.GetAll()` which creates an unnecessary garbage-producing array.


```lua
ply:getJobTable().name
```
Reason: Directly reading `ply:GetNWString("job")` relies on an undocumented network string that DarkRP could rename or remove; `ply:getJobTable()` is the official, stable DarkRP API that provides the full job table and is guaranteed to work across versions.


```lua
if vec1:DistToSqr(vec2) <= thresholdSqr then
    -- within range, no sqrt needed
end
```

Reason: `DistToSqr` avoids the expensive `math.sqrt()` call that `Distance` performs internally, since comparing against the squared threshold yields the same boolean result.


```lua
local NET_STATE_AMOUNT = util.AddNetworkString("gmod_bench_state_amount")

function SendStateAmount(recipients, state, amount)
    if not istable(recipients) then recipients = { recipients } end
    net.Start(NET_STATE_AMOUNT)
    net.WriteUInt(state | (amount << 3), 13)
    net.Send(recipients)
end

net.Receive(NET_STATE_AMOUNT, function(len, ply)
    local packed = net.ReadUInt(13)
    local state = packed & 0x7
    local amount = packed >> 3
    -- consumer hook here
end)
```

Reason: Packs 3-bit state and 10-bit amount into a single 13-bit uint (fits far below the 32-bit WriteUInt ceiling, saving one header byte vs WriteUInt(16) and 3 bytes vs two separate WriteUInt calls). Recipient fanout uses net.Send with a filtered table directly, avoiding net.Broadcast + recipient-side filtering. The optimizations are deliberately asymmetric (client-side receives the same uint but only extracts — no separate decode work is needed at server-defined performance).


Uses an object hook identifier so invalid objects are removed automatically.

```lua
function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, function()
        if not IsValid(self) then return end
        self:Think()
    end)
end
```
Reason: Passing the entity as the `name` (second) argument to `hook.Add` ties the hook to that entity's lifetime; the hook system automatically removes it when the entity is removed, preventing dangling references.


Loading is correct, but server authority or caller authorization is incomplete.

```lua
-- lua/autorun/myaddon.lua (entry point, both realms)
if SERVER then
  AddCSLuaFile("myaddon/shared.lua")
  include("myaddon/shared.lua")
  include("myaddon/sv_damage.lua")
end
if CLIENT then
  include("myaddon/shared.lua")
end

-- lua/myaddon/shared.lua (transferred to + loaded on both realms)
MYADDON = MYADDON or {}

function MYADDON.GetSharedData()
  return { version = 1 }
end

-- lua/myaddon/sv_damage.lua (server only, never sent to client)
function MYADDON.ApplyDamage(ply, ent, dmg)
  if not IsValid(ply) or not ply:IsPlayer() then return false end
  if not IsValid(ent) then return false end
  ent:TakeDamageInfo(dmg)
  ent:SetPhysicsAttacker(ply)
  return true
end
```
Reason: `AddCSLuaFile` transfers `myaddon/shared.lua` to clients and `include` loads it on both realms, while `ApplyDamage` lives in a `sv_` file (never sent to client) and guards `ply` via `IsValid` + `IsPlayer` before acting on the entity.


```lua
local ents = ents.FindInSphere(ply:GetPos(), 512)
for _, ent in ipairs(ents) do
    if ent:IsPlayer() then continue end
    -- process nearby entity
end
```

Reason: FindInSphere uses the engine's spatial hash (O(1) average vs FindInBox's 6-float AABB compare), making it the fastest geometry-based query in benchmarks — no box precomputation, no PVS dependency, and directly expresses the "near a point" semantics.


```lua
local cache = {}
cache[ply] = value  -- store
local val = cache[ply]  -- read
```
Reason: Accessing a plain local table keyed by the player object bypasses the Player metatable's `__index`/`__newindex` overhead entirely, making reads a direct hash lookup instead of a metatable traversal.


```lua
local function FindPlayersNear(pos, radius)
    local players = {}
    local radiusSq = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSq then
            players[#players + 1] = ply
        end
    end
    return players
end
```
Reason: `player.GetAll()` iterates only the player count (typically <100) instead of the entire entity list (often 1000s of props/ragdolls/effects), and `DistToSqr` avoids the sqrt of `pos:Distance()`, making the inner check a single ALU compare.


```lua
local white = Color(255,255,255)
-- inside paint loop: surface.SetDrawColor(white) instead of surface.SetDrawColor(Color(255,255,255))
```

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


```lua
for i = 1, n do
  -- body
end
```
Reason: LuaJIT (which Garry's Mod uses) compiles the numeric `for` loop into a single specialized bytecode pair (`FORPREP`/`FORLOOP`) that avoids per-iteration bounds checks and local variable overhead, while `while` requires explicit comparison, increment, and assignment bytecodes that resist JIT specialization.


```lua
local ply = LocalPlayer()
local health = ply:Health()
-- Use `health` instead of `ply:Health()` for all three draw calls
```

Reason: `LocalPlayer()` and `:Health()` each cross the Lua/C++ boundary and allocate; caching them to local variables eliminates two redundant `LocalPlayer()` calls and two redundant `:Health()` calls per frame.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```
Reason: Global table lookups (math.sin) are hashed key lookups each iteration; assigning the function to a local variable captures a direct reference, eliminating the hash lookup on every call.


Does not define the integer Power datatable variable.

```lua
ENT:NetworkVar("Int", "Power")
```

Reason: `NetworkVar` uses Garry's Mod's built-in data table (DT) system, the preferred entity state primitive that provides automatic prediction, replication only on value change, and generates optimal type-safe getter/setter methods for frequently read values.


```lua
local ply = LocalPlayer()
-- use ply instead of LocalPlayer() everywhere
```
Reason: Storing LocalPlayer() in a local variable avoids a C function call + entity lookup + metamethod dispatch on every access; locals are resolved once at compile time and directly reference the table in the upvalue slot.


```lua
transfers = transfers or {}

local function cancelTransfer(player)
	local data = transfers[player]
	if not data then return end
	local peer = data.peer
	transfers[player] = nil
	if peer and transfers[peer] and transfers[peer].peer == player then
		transfers[peer] = nil
	end
	if IsValid(peer) then
		notifyCancelled(peer)
	end
end

hook.Add("PlayerDisconnected", "TransferLifecycleCleanup", function(player)
	cancelTransfer(player)
end)

timer.Create("TransferLifecycleTimer", 1, 0, function()
	local now = SysTime()
	local expired = {}
	for k, v in pairs(transfers) do
		if IsValid(k) and v.lastActivity and now - v.lastActivity > 30 then
			expired[#expired + 1] = k
		end
	end
	for _, player in ipairs(expired) do
		cancelTransfer(player)
	end
end)
```

Reason: Mutual cleanup via reciprocal peer references — each transfer has two symmetric entries, so cancelling either player removes both. Disconnect hook and 1‑second timer reuse the same `cancelTransfer`; timeout check precollects expired keys to avoid mid‑iteration mutation.


```lua
local function LookingAtEachOther(ply_a, ply_b)
    local a_fwd = ply_a:EyeAngles():Forward()
    local b_fwd = ply_b:EyeAngles():Forward()
    local to_b = (ply_b:GetPos() - ply_a:GetPos())
    local to_a = -to_b
    to_b:Normalize()
    to_a:Normalize()
    return a_fwd:Dot(to_b) > 0.5 and b_fwd:Dot(to_a) > 0.5
end
```

Reason: Dot products of unit vectors are a single multiply-add per axis (vs acos which is ~10-40x slower), and a threshold of 0.5 corresponds to a ~60° cone — good enough for "roughly looking" without the transcendental penalty.


Caches stable render resources and derives per-frame values once.

```lua
local mat = Material("icon16/heart.png")
local col = Color(255, 0, 0)

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

    local hp = ply:Health()
    surface.SetDrawColor(col)
    surface.SetMaterial(mat)
    surface.DrawTexturedRect(10, 10, 32, 32)
    surface.SetTextColor(col)
    surface.SetTextPos(48, 14)
    surface.DrawText(hp)
end)
```
Reason: Material and color are created once outside the per-frame hot path; LocalPlayer is fetched once and guarded by IsValid for early exit; health is cached locally to avoid redundant method calls; the pre-allocated color reference is reused across draw calls instead of constructing a new table every frame.


Core 2/8: interaction, no-broadcast-menu. Missing core: targeted-open, server-authoritative, item-validation, affordability, purchase-order, no-client-authority. Hardening 0/3: none. Missing hardening: proximity, rate-limit, payload-bound.

```lua
-- DarkRP Shop NPC
-- Place in garrysmod/addons/shopnpc/lua/entities/ent_shop_npc.lua

AddCSLuaFile()

DEFINE_BASECLASS("base_entity")

ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Shop NPC"
ENT.Author = "DarkRP"
ENT.Category = "DarkRP"
ENT.Spawnable = true
ENT.AdminOnly = false

function ENT:SetupDataTables()
    self:NetworkVar("String", 0, "ShopName")
    self:NetworkVar("String", 1, "ShopCategory")
end

if SERVER then
    function ENT:Initialize()
        self:SetModel("models/humans/group01/male_09.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
        self:SetShopName("Shop")
        self:SetShopCategory("default")
    end

    function ENT:AcceptInput(name, activator, caller)
        if name == "Use" and IsValid(activator) and activator:IsPlayer() then
            self:OpenShop(activator)
        end
    end

    function ENT:OpenShop(ply)
        local items = {}
        for _, item in ipairs(DarkRP.getItems() or {}) do
            if item.category == self:GetShopCategory() or self:GetShopCategory() == "all" then
                table.insert(items, {
                    name = item.name,
                    price = item.price,
                    cmd = item.cmd,
                    category = item.category,
                    model = item.model or "models/props_cuboids/cuboid_2x2x2.mdl"
                })
            end
        end
        net.Start("ShopNPC_Open")
        net.WriteEntity(self)
        net.WriteUInt(#items, 16)
        for _, v in ipairs(items) do
            net.WriteString(v.name)
            net.WriteUInt(v.price, 32)
            net.WriteString(v.cmd)
            net.WriteString(v.category)
            net.WriteString(v.model)
        end
        net.Send(ply)
    end
end

if CLIENT then
    local PANEL = {}

    function PANEL:Init()
        self:SetSize(ScrW() * 0.4, ScrH() * 0.6)
        self:Center()
        self:SetTitle("Shop")
        self:SetDraggable(true)
        self:ShowCloseButton(true)
        self:MakePopup()

        self.itemList = vgui.Create("DListView", self)
        self.itemList:Dock(FILL)
        self.itemList:SetMultiSelect(false)
        self.itemList:AddColumn("Item")
        self.itemList:AddColumn("Price")
        self.itemList:AddColumn("Category")

        self.buyButton = vgui.Create("DButton", self)
        self.buyButton:SetText("Buy")
        self.buyButton:Dock(BOTTOM)
        self.buyButton:SetTall(32)
        self.buyButton.DoClick = function()
            local selected = self.itemList:GetSelectedLine()
            if not selected then return end
            local data = self.itemList:GetLine(selected)
            RunConsoleCommand("darkrp", "buy", data.cmd)
            self:Close()
        end
    end

    net.Receive("ShopNPC_Open", function()
        local ent = net.ReadEntity()
        if not IsValid(ent) then return end
        local count = net.ReadUInt(16)
        local frame = vgui.Create("DFrame")
        frame:SetSize(ScrW() * 0.4, ScrH() * 0.6)
        frame:Center()
        frame:SetTitle(ent:GetShopName())
        frame:SetDraggable(true)
        frame:ShowCloseButton(true)
        frame:MakePopup()

        local list = vgui.Create("DListView", frame)
        list:Dock(FILL)
        list:SetMultiSelect(false)
        list:AddColumn("Item")
        list:AddColumn("Price")
        list:AddColumn("Category")

        for i = 1, count do
            local name = net.ReadString()
            local price = net.ReadUInt(32)
            local cmd = net.ReadString()
            local category = net.ReadString()
            local model = net.ReadString()
            local line = list:AddLine(name, DarkRP.formatMoney(price), category)
            line.cmd = cmd
        end

        local buy = vgui.Create("DButton", frame)
        buy:SetText("Buy")
        buy:Dock(BOTTOM)
        buy:SetTall(32)
        buy.DoClick = function()
            local selected = list:GetSelectedLine()
            if not selected then return end
            local line = list:GetLine(selected)
            RunConsoleCommand("darkrp", "buy", line.cmd)
            frame:Close()
        end
    end)
end

list.Set("DarkRPEntities", "ent_shop_npc", {
    PrintName = "Shop NPC",
    Category = "NPCs",
    Spawnable = true,
    AdminOnly = false,
    Material = "entities/ent_shop_npc.png"
})
```

Reason: This is a complete, self-contained DarkRP shop NPC entity that spawns a human NPC, opens a DFrame shop UI on use, lists items filtered by category from DarkRP's item registry, and triggers the `darkrp buy` console command on purchase — all within a single file following standard DarkRP entity conventions.


```lua
-- Faster: one hook.Run call with all players
hook.Run("Tick", player.GetAll())
```
Reason: `hook.Run` has non-trivial overhead per call (hook table lookup, pcall wrapping, function dispatch). Calling it N times multiplies that overhead. One call passes the whole player table — each listener loops internally, but that's a plain Lua loop with zero hook overhead.


```lua
local _ang = Angle()
-- reuse in hot path with: _ang:Zero()
```

Reason: `Angle()` allocates a new C++ userdata every call; reusing a pre-allocated Angle and calling `:Zero()` (a C-side memset) avoids allocation entirely, which is critical in hot paths where GC pressure kills framerate.


```lua
local SomeHelper = function(ply) end  -- defined locally

-- Call it:
SomeHelper(ply)
```

Reason: Local variable access (register/upvalue) is faster than a method table lookup (`ply:SomeHelper()` requires a metatable search for the function), and using a local avoids the hash lookup and extra `self` push.


```lua
for i = 1, #t do
  local v = t[i]
end
```
Reason: Numeric for avoids per-iteration function call overhead (no iterator call like pairs/ipairs), uses direct VM bytecode for bounds checking, and Lua's internal array part delivers O(1) index access — making it 2-5x faster than ipairs and 5-10x faster than pairs on large sequential tables.


```lua
local msg = Msg
msg("debug line\n")
```
Reason: `print()` calls `tostring()` on each argument, inserts tabs, and appends a newline — overhead that `Msg()` skips, and localizing the reference avoids global table lookup.


```lua
local cachedPlayers = {}

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

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

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

Reason: `player.GetAll()` allocates a new table each call; caching it avoids per-tick GC pressure and table allocation, refreshing only on join/leave hooks where the player list actually changes.


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

Reason: Passing separate number arguments avoids the overhead of constructing a Color object (table allocation + metatable setup), which matters in hot draw paths like HUDPaint.


```lua
sql.Query("SELECT * FROM players WHERE steamid = ?", steamid)
```

Reason: Local SQLite avoids network round-trip latency by reading/writing directly to a local file, while MySQL requires TCP/IP communication to a remote server.


```lua
local steamid_cache = {}
function GetCachedSteamID(ply)
  local sid = steamid_cache[ply]
  if not sid then
    sid = ply:SteamID()
    steamid_cache[ply] = sid
    ply:OnRemove(function() steamid_cache[ply] = nil end) -- prevent dangling ref
  end
  return sid
end
```
Reason: `ply:SteamID()` does a C→Lua call + string allocation every invocation; caching with a weak-keyed table keyed on the player object avoids repeated string generation and keeps the cache clean without manual removal.


```lua
local zangle = Angle() -- created once outside the hot path
-- hot path reuses zangle: zangle:Set(0, 0, 0) or just read it
```
Reason: `Angle()` allocates C-side userdata and sets up metatables on every call; a hoisted local avoids all allocation and lookup overhead in the hot path.


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

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

Reason: `..` allocates a new string on every operation (O(n²) total), while `table.concat` precomputes the total length, allocates once, and copies each piece in O(n).


```lua
-- fn approach (slow)
local result = fn.Compose(
  fn.Filter(fn.Curry(fn.Select, 2)(IsValid)),
  fn.Map(fn.Curry(fn.Select, 2)(function(ply) return ply:Nick() end))
)(entities)

-- plain loop (fast)
local result = {}
for i = 1, #entities do
  local e = entities[i]
  if IsValid(e) then
    result[#result + 1] = e:Nick()
  end
end
```
Reason: fn chains allocate a closure and a new table per combinator per call; a single for loop eliminates all per-element function-call overhead and intermediate allocations, running the entire pipeline in one pass.


Chunk receiver satisfies 12/20 state and size checks.

```lua
local NET_CHUNK = "MyAddon.Chunk"

local MAX_CHUNKS = 64
local MAX_CHUNK_SIZE = 24000
local MAX_AGGREGATE = 1048576

net.Receive(NET_CHUNK, function(len, ply)
    if not IsValid(ply) then return end

    local id = net.ReadUInt(32)
    local index = net.ReadUInt(16)
    local size = net.ReadUInt(16)

    if size > net.BytesLeft() then return end
    if size > MAX_CHUNK_SIZE then return end
    if index < 1 or index > MAX_CHUNKS then return end

    local transfer = MyAddon.transfers[ply]
    if not transfer then return end
    if transfer.id ~= id then return end
    if transfer.chunks[index] ~= nil then return end

    local newTotal = transfer.totalBytes + size
    if newTotal > MAX_AGGREGATE then return end

    local data = net.ReadData(size)
    transfer.chunks[index] = data
    transfer.received = transfer.received + 1
    transfer.totalBytes = newTotal
    transfer.lastActivity = CurTime()
end)
```
Reason: Pooled string once at module scope; validated header fields left-to-right before touching state; rejected on invalid ply, wrong transfer id, out-of-range index, duplicate chunk, declared size > bytes left, per-chunk or aggregate overflow before net.ReadData to guarantee clean partial-read rejection; stored data, incremented received, summed totalBytes, and bumped lastActivity.


```lua
-- Fast: sequential array with numeric for loop
local t = {"a", "b", "c"}
for i = 1, #t do
  local v = t[i]
end
```

Reason: Numeric-keyed arrays use the table's array part (contiguous memory, O(n) sequential access) and a plain `for` loop has zero iterator overhead, while string-keyed maps use the hash part (sparse, pointer-chasing, O(n) with higher constant factors) and `pairs` must skip nil hash slots and call a C iterator function per step.


```lua
#t
```

Reason: The `#` operator is the preferred and most efficient way to get the length of a sequential array-like table in Garry's Mod Lua (Lua 5.1), as `table.Count` is a GMod wrapper that iterates the entire table with `pairs()` and is O(n) regardless of sequence holes.


```lua
local result = x * x
```
Reason: In GMod Lua (Lua 5.1 derived), `x * x` avoids the function call overhead of `math.pow(x, 2)` and the generic exponentiation path of `x ^ 2`, which is significantly slower in tight loops.


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

Reason: table.HasValue iterates the entire list O(n) on every check, while a lookup table uses Lua's hash-based table access O(1) — the key is hashed and found directly without scanning.


```lua
surface.CreateFont("OptimizedFont", {font = "Arial", size = 18, weight = 500})
hook.Add("HUDPaint", "FastDraw", function()
    surface.SetFont("OptimizedFont")
    surface.SetTextPos(10, 10)
    surface.SetTextColor(255, 255, 255, 255)
    surface.DrawText("Hello")
end)
```

Reason: Using raw `surface.*` calls avoids `draw.DrawText`'s per-frame font-lookup and property-reset overhead; the font is created once via `surface.CreateFont` and only position/color/draw are issued each frame.


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

Reason: `draw.RoundedBox(0, ...)` still computes and submits a mesh with bezier interpolation for all four corners before discarding it, while `surface.DrawRect` calls the engine's native rectangle rasterizer directly with zero superfluous math.


```lua
timer.Simple(1, function() if IsValid(ent) then ent:Remove() end end)
```
Reason: timer.Simple schedules a one-shot callback after 1 second; IsValid guards against removing an already-removed entity.


Receiver includes 6/11 required trust-boundary checks.

```lua
local spam = {}

net.Receive("MyAddon.SetPower", function(_, ply)
    if not IsValid(ply) or not ply:IsAdmin() then return end

    local now = CurTime()
    if spam[ply] and now - spam[ply] < 0.5 then return end
    spam[ply] = now

    local ent = net.ReadEntity()
    local power = net.ReadUInt(7)
    if not IsValid(ent) then return end

    if isfunction(ent.CPPIGetOwner) then
        local owner = ent:CPPIGetOwner()
        if IsValid(owner) and owner ~= ply then return end
    end

    ent:SetPower(math.Clamp(power, 0, 100))
end)
```
Reason: Gates on admin + ownership (CPPI), rate-limits at 0.5s per player, discards invalid entities, and clamps the 7-bit unsigned read to 0–100 before calling SetPower.


```lua
t = {}
```
Reason: `t = {}` is O(1) — it simply creates a new empty table and reassigns the reference, while `table.Empty(t)` is O(n) because it must iterate and clear every element in the existing table.


Guards the whole attack, preventing predicted state updates on replay.

```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
    if not IsFirstTimePredicted() then return end
    self:ShootBullet(self.Primary.Damage, self.Primary.NumShots, self.Primary.Tracer)
    self:EmitSound(self.Primary.ShootSound)
    util.Effect(self.Primary.Effect, EffectData())
end
```

Reason: `SetNextPrimaryFire` must run on every prediction pass (client and server) so the fire rate stays synchronized; `util.Effect`, `EmitSound`, and `ShootBullet` dispatch only on the first predicted frame to avoid duplicate world effects, matching the Prediction–Reliable–Spawn–Effects pattern in Source multiplayer.


```lua
local tbl = { ... }
return tbl[math.random(#tbl)]
```
Reason: table.Random calls table.GetKeys to build a key array, then indexes into that — for sequential tables, #tbl gives the count directly, avoiding the O(n) key scan and allocation.


Payload receiver satisfies 9/11 bounded-decompression checks.

```lua
local NET_STRING = "MyAddon.Upload"

util.AddNetworkString(NET_STRING)

net.Receive(NET_STRING, function(len, ply)
    if not ply:IsAdmin() then return end
    if len < 1 or len > 32768 then return end

    local compressed = net.ReadData(len)
    if #compressed ~= len then return end

    local ok, decoded = pcall(util.Decompress, compressed)
    if not ok or #decoded > 262144 then return end

    consume(decoded)
end)
```
Reason: `util.Decompress` on invalid LZMA data throws an error; wrapping it in `pcall` and checking `#decoded > 262144` rejects both decompression failures and oversized output. `len` caps compressed input at 32 KiB before reading.


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

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

Reason: `player.GetAll()` returns a sequential array table, so `ipairs` is the correct iterator — `pairs` works but adds unnecessary hash-table lookup overhead for a dense numeric sequence.


```lua
local data = setmetatable({}, { __mode = "k" })
-- write: data[ply] = { hp = 100 }
-- read: data[ply].hp
```

Reason: Storing per-player data in a weak-keyed (mode `"k"`) local table avoids Player metatable overhead from `__index`/`__newindex` metamethods on every field access, and using the entity itself as a table key avoids the `EntIndex()` function call cost on reads.


```lua
for ent in ents.Iterator("prop_physics") do
end
```
Reason: `ents.Iterator("prop_physics")` returns a direct entity iterator that yields each matching entity one at a time without allocating or returning a table of all results, unlike `ents.FindByClass` which builds and returns the full list.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: GMod's `hook.Add` uses a string identifier as the second argument to uniquely register or override the callback, allowing later removal via `hook.Remove("Think", "MyAddon.Think")`.


```lua
-- lua/autorun/myaddon.lua
if SERVER then
    AddCSLuaFile("myaddon/shared.lua")
end
include("myaddon/shared.lua")

-- myaddon/shared.lua
if SERVER then
    util.AddNetworkString("myaddon.ApplyDamage")
end

function ApplyDamage(ent, dmg)
    if not SERVER then return end
    if not IsValid(ent) then return end
    local attacker = dmg:GetAttacker()
    if not IsValid(attacker) or not attacker:IsPlayer() then return end
    ent:TakeDamageInfo(dmg)
end
```
Reason: `AddCSLuaFile` in `SERVER` block marks the file for client download; `include` on both realms loads it unconditionally. `ApplyDamage` guards on `SERVER`, validity of the entity, and that the attacker is a player, making damage server-authoritative.


```lua
if IsValid(ent) then ent:SomeMethod() end
```
Reason: `IsValid()` checks both that the reference is not `nil` and that the entity hasn't been removed or gone invalid (i.e., it wraps `ent ~= nil and ent:IsValid()` internally), preventing attempts to call methods on a freed or `NULL` entity.


Answer must contain 0 through 0 candidate loops.

```lua
local LIMIT = 10
local WINDOW = 1
local buf = {} -- [steamid64] = { [n]=timestamp }

local function prune(id, since)
  local t = buf[id]
  if not t then t = {}; buf[id] = t end
  local j = 0
  for i = 1, #t do
    if t[i] >= since then j = j + 1; t[j] = t[i] end
  end
  for i = j + 1, #t do t[i] = nil end
  return j
end

local function allow(ply)
  local id = ply:SteamID64()
  local now = SysTime()
  local n = prune(id, now - WINDOW)
  if n >= LIMIT then return false end
  buf[id][n + 1] = now
  return true
end

hook.Add("PlayerSpawnProp", "SpawnRateLimit", function(ply, _)
  if not IsValid(ply) then return end
  if not allow(ply) then return false end
end)

hook.Add("PlayerSpawnSENT", "SpawnRateLimit", function(ply, _)
  if not IsValid(ply) then return end
  if not allow(ply) then return false end
end)

hook.Add("PlayerDisconnected", "SpawnRateLimit", function(ply)
  buf[ply:SteamID64()] = nil
end)
```
Reason: Pre-spawn hooks (`PlayerSpawnProp` / `PlayerSpawnSENT`) return `false` (deny) when the rolling `SysTime` window exceeds 10, returning `nil` (pass-through) otherwise so other addons' hooks still fire; per-player state is freed in `PlayerDisconnected`.