```lua
local CachedPlayers = {}

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

hook.Add("PlayerConnect", "RefreshPlayerCache", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCache", RefreshPlayerCache)
RefreshPlayerCache()

hook.Add("Tick", "CachedPlayerTick", function()
    for _, ply in ipairs(CachedPlayers) do
        if IsValid(ply) then
            -- per-tick logic here
        end
    end
end)
```
Reason: Caching the player list and updating only on join/leave hooks avoids repeated table allocation and full player scans every tick.


```lua
local pdata = setmetatable({}, { __mode = "k" }) -- weak keys for auto cleanup

-- store temporary data:
pdata[ply] = { score = 0, buff = 2 }

-- fast read (no metatable lookup on entity):
local score = pdata[ply].score
```
Reason: Plain table lookup avoids entity metatable __index overhead, making frequent reads faster than ply.field access.


```lua
local arr = { "x", "y", "z" }
for i = 1, #arr do
    local val = arr[i]
end
```
Reason: Sequential number-indexed arrays iterate via integer keys and # length, avoiding hash lookups and pairs overhead, making them faster than string-keyed maps.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate numbers avoids Color object allocation, reducing garbage and call overhead in hot draw paths.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: Local SQLite avoids network round-trips, giving lower read/write latency than remote MySQL for a single server.


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

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

hook.Add("PlayerDisconnected", "SteamIDCache_Clear", function(ply)
    steamIDCache[ply] = nil
end)
```
Reason: Caches SteamID per player in a weak-keyed table to avoid repeated calls and auto-clears on disconnect.


OpenRouter message content was empty or missing.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect avoids the corner-radius branching and extra math in draw.RoundedBox, making it slightly faster for axis-aligned rectangles.


```lua
surface.SetFont("Default")
hook.Add("HUDPaint", "FastSingleLine", function()
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Single-line string")
end)
```
Reason: surface.DrawText is the lowest-level text primitive and avoids the extra function calls, table creation, and outline passes used by draw.DrawText and draw.SimpleTextOutlined, making it fastest for plain single-line text.


```lua
local length = #myArray
```
Reason: The # length operator is the preferred, idiomatic way to get the size of a sequential array-like table in Lua (and thus GMod).


```lua
t = {}
```
Reason: Reassigning to a new empty table avoids iterating over all elements, making it faster than table.Empty for large sequential tables when no other references are held.


Answer must contain 0 through 0 candidate loops.

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

if set["b"] then
    print("value exists")
end
```
Reason: Building a hash set gives O(1) membership checks instead of O(n) linear scans like table.HasValue.


```lua
local t = { x = 10, y = 20, name = "example" }
```
Reason: Using the table constructor initializes all fields in a single allocation/instruction sequence, avoiding separate setter calls and thus is faster than assigning after {}.


```lua
local function randomFromSeq(t)
    return t[math.random(#t)]
end
```
Reason: Direct indexed access with math.random on array length is O(1) and avoids table.Random's pair iteration and counting overhead.


```lua
local sq = x * x
```
Reason: Direct multiplication is faster than using the ^ operator or math.pow in Lua tight loops.


Keeps pairs() rather than Iterator or a cached numeric for-loop.

```lua
for _, ply in pairs(player.GetAll()) do
end
```
Reason: Uses player.GetAll() to obtain the list of connected players and iterates over it with pairs.


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

Reason: ents.FindByClass returns only entities of the given class, avoiding iterating all map entities first.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```
Reason: Uses hook.Add to register an empty callback on the Think hook with the identifier MyAddon.Think.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: IsValid checks that ent is a non-null valid entity not pending removal, preventing errors from stale references.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming net message here
end)
```
Reason: net.Receive registers a callback that runs when a net message with the given name is received from the client or server.


```lua
local ZeroAngle = Angle(0, 0, 0)
-- reuse ZeroAngle instead of calling Angle() repeatedly
```
Reason: Reusing a preallocated zeroed Angle avoids repeated constructor overhead in hot paths.


```lua
local myaddon_color = Color(255, 0, 0)
local read = myaddon_color
```
Reason: Flat local variables avoid table lookups, making reads faster than nested table accesses.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP provides getDarkRPVar("job") as the proper networked variable accessor, avoiding fragile direct NWString usage.


```lua
if (vecA:DistToSqr(vecB) <= threshold * threshold) then
    -- within threshold
end
```
Reason: DistToSqr avoids the square root and is the preferred method for threshold distance checks.


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

Reason: ents.GetAll() returns a table of all entities which ipairs iterates efficiently as recommended on the GMod wiki.


```lua
local ply = Entity(1)
local radius = 256
local ents = ents.FindInSphere(ply:GetPos(), radius)
```
Reason: ents.FindInSphere is a commonly benchmarked fast built-in spatial query that avoids PVS overhead for small-radius nearby entity checks.


```lua
local found = {}
local pos = Vector(0, 0, 0)
local radius = 512
local radiusSq = radius * radius

for _, ply in ipairs(player.GetAll()) do
    if ply:GetPos():DistToSqr(pos) <= radiusSq then
        found[#found + 1] = ply
    end
end
```
Reason: Iterating player.GetAll() and using DistToSqr avoids entity table scans and sqrt, making it faster with many players.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Lua's numeric for loop is generally faster than while because it precomputes the limit and step and avoids explicit index increments and condition checks in Lua code.


```lua
-- Faster: call hook.Run once with the whole player table
hook.Run("TickAllPlayers", player.GetAll())

-- Slower: loop and call hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("TickPlayer", ply)
end
```
Reason: A single hook.Run avoids repeated hook iteration/dispatch overhead, making the batch call faster than per-player calls.


```lua
hook.Add("HUDPaint", "FastHealthDraw", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText(hp, "Default", 10, 10, Color(255, 255, 255))
    draw.SimpleText(hp, "Default", 10, 30, Color(255, 0, 0))
    draw.SimpleText(hp, "Default", 10, 50, Color(0, 255, 0))
end)
```
Reason: Caching LocalPlayer():Health() in a local avoids three separate function calls and is faster.


```lua
local white = Color(255, 255, 255)
hook.Add("HUDPaint", "example", function()
    surface.SetDrawColor(white)
    -- draw operations
end)
```

Reason: Reusing a preallocated Color table avoids per-frame allocation and garbage collection overhead.


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

Reason: Localizing the function avoids repeated table lookups on math each call.


```lua
local ply = LocalPlayer()
hook.Add("PlayerSpawn", "UpdateLocalPly", function(p)
    if p == ply then ply = p end
end)
-- use 'ply' instead of calling LocalPlayer() repeatedly
```

Reason: Caching the LocalPlayer reference in a local variable avoids repeated global/engine lookups, and the spawn hook keeps it valid after respawns.


```lua
local function lookingAtEachOther(p1, p2)
    local d = p2:GetPos() - p1:GetPos()
    local f1 = p1:GetAimVector()
    local f2 = p2:GetAimVector()
    return f1:Dot(d) > 0 and f2:Dot(-d) > 0
end
```

Reason: Dot product with direction vectors is cheaper than acos and checks if aims point toward each other's positions.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid metamethod/lookup overhead and are faster than colon method calls for helpers you control.


```lua
debug.getregistry().Console and debug.getregistry().Console("debug message\n") or Msg("debug message\n")
```
Reason: Msg avoids print's vararg formatting overhead and is the standard fast console output in GMod Lua hot paths.


```lua
local t = {1,2,3,4,5}
for i=1,#t do
    local v = t[i]
end
```
Reason: Numeric for with #t is fastest because it avoids iterator function overhead of pairs/ipairs and directly indexes the array.


```lua
local players = player.GetAll()
local result = {}
for i = 1, #players do
    local p = players[i]
    if IsValid(p) and p:isDarkRPAdmin() then
        local name = p:Nick()
        if #name > 3 then
            result[#result + 1] = string.upper(name)
        end
    end
end
```
Reason: A single tight loop with early checks avoids fn's closure overhead and intermediate tables, making it faster than combinator chaining.


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

gameevent.Listen("player_connect")
hook.Add("player_connect", "RefreshPlayerCache", function()
    cachedPlayers = player.GetAll()
end)

gameevent.Listen("player_disconnect")
hook.Add("player_disconnect", "RefreshPlayerCache", function()
    cachedPlayers = player.GetAll()
end)

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- do per-player work here
    end
end)
```
Reason: Caching player.GetAll() and only rebuilding it on join/leave events avoids repeated table allocation and iteration setup every tick.


```lua
local plyData = setmetatable({}, {__mode = "k"})
local function getPlyData(ply)
    local d = plyData[ply]
    if not d then
        d = {}
        plyData[ply] = d
    end
    return d
end

-- write:
getPlyData(ply).score = 100
-- read (fast, local-table indexed):
local score = getPlyData(ply).score
```

Reason: Using a local weak-keyed table avoids metatable/field lookups on the Entity and keeps hot data in a plain Lua table for faster reads.


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

Reason: Sequential numeric arrays with ipairs-style or count-based loops avoid hash lookups and are faster than iterating string-keyed maps in Lua.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate numbers avoids creating a Color object each frame, reducing allocation and GC overhead in hot draw paths.


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

Reason: Local SQLite avoids network round-trips so reads/writes have lower latency than remote MySQL for single-server use.


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

local function GetCachedSteamID(ply)
    local id = steamIDCache[ply]
    if not id then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```
Reason: Caches SteamID per player in a weak-keyed table to avoid repeated native calls while allowing GC of disconnected players.


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


```lua
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect skips the rounding logic in draw.RoundedBox and issues a direct rect draw, making it faster for non-rounded boxes.


```lua
hook.Add("HUDPaint", "FastText", function()
    draw.SimpleTextOutlined("Hello", "DermaDefault", 100, 100, Color(255,255,255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, Color(0,0,0))
end)
```
Reason: draw.SimpleTextOutlined batches text drawing internally and avoids per-call font/color state setup overhead compared to manual surface.* calls.


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

Reason: The length operator # is the idiomatic and efficient way to get the length of a sequential array-like table in Lua.


```lua
t = {}
```

Reason: Reassigning to a new empty table is faster than clearing in-place because it avoids iterating over all existing entries and lets the old table be garbage-collected.


```lua
local set = { ["value1"] = true, ["value2"] = true }
if set["value1"] then
    -- value exists
end
```
Reason: Using a hash table with true values allows O(1) lookups, unlike table.HasValue which does a slow O(n) linear scan.


```lua
local t = {x = 1, y = 2, z = 3}
```
Reason: Using the table constructor avoids extra key assignments and is faster for known fields.


```lua
local function fastRandom(t)
    return t[math.random(#t)]
end
```
Reason: Using math.random with the table length directly avoids table.Random's extra table size lookup and function overhead for sequential tables.


```lua
local y = x * x
```
Reason: Multiplication is faster than math.pow and avoids function call overhead in tight loops.


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

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

Reason: Using ipairs with player.GetAll() cleanly iterates over the list of currently connected players.