```lua
local squared = x * x
```
Reason: Multiplication avoids the slower exponentiation operator and is the preferred fast form for squaring in tight loops.


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

```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: player.Iterator() visits the current connected players without creating the player.GetAll() table first.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent here
    end
end
```
Reason: ents.Iterator() walks entities lazily, so it avoids ents.GetAll() building a full map-wide entity table.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a function on the `Think` hook using `MyAddon.Think` as its unique identifier.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` returns false for nil, NULL, or removed entities, so methods are only called on usable entity references.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Read message data here.
end)
```
Reason: net.Receive registers a callback for the named incoming net message.


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

-- Hot path: faster than Angle() because it reuses the C-side zero constant
-- and only allocates when you explicitly copy it.
local function FreshZeroAngle()
    return Angle(ZERO_ANGLE)
end
```
Reason: Constructing from a cached zero Angle avoids parsing/default construction work on each call while still returning a separate mutable Angle.


```lua
local configColor = Color(255, 80, 80)

local color = configColor
```
Reason: A flat local is fastest because it avoids global lookup and repeated table indexing on every read.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores the player-visible job name in DarkRPVars; use `getDarkRPVar("job")` instead of reading the raw NW string directly.


```lua
local maxDistance = 500

if posA:DistToSqr(posB) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `DistToSqr` avoids calculating a square root, so it is preferred when you only need a threshold check.


```lua
for ent in ents.Iterator() do
    -- Visit ent here.
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient choice when you only need to iterate, because it avoids allocating the table returned by `ents.GetAll()`.


Answer must contain 0 through 0 candidate loops.

```lua
local RADIUS = 512
local RADIUS_SQR = RADIUS * RADIUS
local EXTENTS = Vector(RADIUS, RADIUS, RADIUS)

local function FindEntitiesNearPlayer(ply)
    if not IsValid(ply) then return {} end

    local origin = ply:GetPos()
    local candidates = ents.FindInBox(origin - EXTENTS, origin + EXTENTS)
    local nearby = {}

    for i = 1, #candidates do
        local ent = candidates[i]
        if ent ~= ply and IsValid(ent) and ent:GetPos():DistToSqr(origin) <= RADIUS_SQR then
            nearby[#nearby + 1] = ent
        end
    end

    return nearby
end
```
Reason: `ents.FindInBox` is commonly one of the faster built-in broad-phase queries; the `DistToSqr` filter keeps true radius behavior without a square root.


```lua
local function FindPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local players = player.GetAll()
    local found = {}
    local count = 0

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

    return found
end
```
Reason: This only iterates players and uses squared distance, avoiding `ents.FindInSphere` collecting nearby non-player entities and then filtering them.


```lua
for i = 1, n do
    -- work
end
```
Reason: Numeric for loops are generally faster in GMod Lua because the VM/JIT has a dedicated numeric-for loop path, avoiding the extra manual compare and increment work of a while loop.


```lua
-- Faster: one hook dispatch per tick, with the player list passed once.
hook.Add("Tick", "MyAddon_TickPlayers_Fast", function()
    hook.Run("MyAddon_TickPlayers", player.GetAll())
end)

hook.Add("MyAddon_TickPlayers", "MyAddon_CustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom per-player logic here
    end
end)

-- Slower pattern to avoid: one hook dispatch per player per tick.
-- hook.Add("Tick", "MyAddon_TickPlayers_Slow", function()
--     local players = player.GetAll()
--     for i = 1, #players do
--         hook.Run("MyAddon_TickPlayer", players[i])
--     end
-- end)
```
Reason: `hook.Run` has dispatch overhead, so doing it once per tick and looping players inside the listener avoids repeated hook lookup/callback dispatch per player.


```lua
local healthBarColor = Color(220, 60, 60)

hook.Add("HUDPaint", "DrawCachedHealth", function()
    local ply = LocalPlayer()
    local health = ply:Health()

    draw.SimpleText("Health: " .. health, "DermaDefault", 20, 20, color_white)
    draw.RoundedBox(4, 20, 42, math.Clamp(health, 0, 100) * 2, 12, healthBarColor)
    draw.SimpleText(health > 0 and "Alive" or "Dead", "DermaDefault", 20, 60, color_white)
end)
```
Reason: `LocalPlayer()` and `:Health()` run once per HUDPaint frame, then the cached `health` value is reused by all three draw calls.


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

hook.Add("HUDPaint", "FastPaint", function()
    for _, item in ipairs(items) do
        draw.SimpleText(item.text, "DermaDefault", item.x, item.y, WHITE)
    end
end)
```
Reason: Cache the Color table once outside the paint loop to avoid per-iteration table allocation and function call overhead.


```lua
local sin = math.sin

local total = 0
for i = 1, iterations do
    total = total + sin(i)
end
```
Reason: `sin` is resolved once, so the hot loop uses a faster local lookup instead of repeatedly indexing `math.sin`.


```lua
local LocalPlayer = LocalPlayer
local IsValid = IsValid

local cachedLocalPlayer

local function GetLocalPlayer()
    if not IsValid(cachedLocalPlayer) then
        cachedLocalPlayer = LocalPlayer()
    end

    return cachedLocalPlayer
end

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

hook.Add("Think", "UseCachedLocalPlayer", function()
    local ply = GetLocalPlayer()
    if not IsValid(ply) then return end

    -- use ply here instead of calling LocalPlayer() repeatedly
    local pos = ply:GetPos()
end)
```
Reason: Cache the player entity once it exists and only refresh it when invalid, so hot paths reuse the same reference instead of repeatedly calling `LocalPlayer()`.


```lua
local LOOK_DOT = 0.70 -- about a 45 degree cone; raise for stricter matching

local function RoughlyLookingAtEachOther(a, b)
    if not IsValid(a) or not IsValid(b) then return false end

    local aEye = a:EyePos()
    local bEye = b:EyePos()

    local aToB = (bEye - aEye):GetNormalized()
    local bToA = -aToB

    return a:GetAimVector():Dot(aToB) >= LOOK_DOT
       and b:GetAimVector():Dot(bToA) >= LOOK_DOT
end
```
Reason: Dot products compare direction alignment against a cosine threshold directly, avoiding the slower `math.acos` angle conversion.


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

SomeHelper(ply)
```
Reason: For a helper you control, a local function call with `ply` as an explicit argument avoids the method lookup behind `ply:SomeHelper()` and is generally faster in hot paths.


```lua
local DEBUG_HOTPATH = false
local msg = Msg

if DEBUG_HOTPATH then
    msg("[my_addon] hot path reached\n")
end
```
Reason: Msg writes the string directly with an explicit newline, avoiding print's extra argument conversion and formatting work.


```lua
local nums = numbers

for i = 1, #nums do
    local n = nums[i]
    -- use n
end
```
Reason: numeric for avoids the generic iterator overhead of pairs/ipairs and is fastest for dense sequential arrays.


```lua
local function richAliveNames(players, minMoney)
    local out = {}
    local n = 0

    for i = 1, #players do
        local ply = players[i]

        if IsValid(ply) and ply:Alive() then
            local money = ply:getDarkRPVar("money") or 0

            if money >= minMoney then
                n = n + 1
                out[n] = ply:Nick()
            end
        end
    end

    return out
end

local names = richAliveNames(player.GetAll(), 10000)
```
Reason: One fused numeric loop avoids DarkRP `fn` closure calls and intermediate filter/map tables, so it does less allocation and dispatch for the same transform.


```lua
if SERVER then
    local cachedPlayers = player.GetAll()
    local cachedPlayerCount = #cachedPlayers
    local cachedPlayerIndex = {}

    for i = 1, cachedPlayerCount do
        cachedPlayerIndex[cachedPlayers[i]] = i
    end

    hook.Add("PlayerInitialSpawn", "MyAddon_CachePlayer", function(ply)
        if cachedPlayerIndex[ply] then return end

        cachedPlayerCount = cachedPlayerCount + 1
        cachedPlayers[cachedPlayerCount] = ply
        cachedPlayerIndex[ply] = cachedPlayerCount
    end)

    hook.Add("PlayerDisconnected", "MyAddon_UncachePlayer", function(ply)
        local index = cachedPlayerIndex[ply]
        if not index then return end

        local lastPlayer = cachedPlayers[cachedPlayerCount]
        cachedPlayers[index] = lastPlayer
        cachedPlayers[cachedPlayerCount] = nil
        cachedPlayerIndex[ply] = nil

        if lastPlayer ~= ply then
            cachedPlayerIndex[lastPlayer] = index
        end

        cachedPlayerCount = cachedPlayerCount - 1
    end)

    hook.Add("Think", "MyAddon_PerPlayerThink", function()
        for i = 1, cachedPlayerCount do
            local ply = cachedPlayers[i]

            -- Per-player tick work here.
        end
    end)
end
```
Reason: `player.GetAll()` and `ipairs` are removed from the hot tick path; joins and leaves update the cache, while Think uses a numeric loop over a stable array.


```lua
local scoreByEntIndex = {}

hook.Add("PlayerDisconnected", "ClearTempPlayerData", function(ply)
    scoreByEntIndex[ply:EntIndex()] = nil
end)

local function SetTempScore(ply, score)
    scoreByEntIndex[ply:EntIndex()] = score
end

local function GetTempScore(ply)
    return scoreByEntIndex[ply:EntIndex()]
end
```
Reason: Numeric side-table reads avoid repeated custom field lookup on the Player object and keep hot temporary data in a plain Lua table.


```lua
local classes = {
    "weapon_pistol",
    "weapon_smg1",
    "weapon_shotgun",
    "weapon_ar2",
}

for i = 1, #classes do
    local class = classes[i]
    -- use class
end
```
Reason: Sequential number-indexed arrays are faster to iterate than string-keyed maps because Lua can walk the array part with direct numeric indexes instead of traversing hash keys.


```lua
local drawR, drawG, drawB, drawA = 255, 80, 40, 255

hook.Add("HUDPaint", "HotDrawPath", function()
    surface.SetDrawColor(drawR, drawG, drawB, drawA)
    surface.DrawRect(32, 32, 160, 24)
end)
```
Reason: Passing raw numeric channels avoids the slower Color table/object path in a hot draw loop.


```lua
local steamID64 = ply:SteamID64()
local rows = sql.Query("SELECT money FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64) .. " LIMIT 1")

if rows and rows[1] then
    print(rows[1].money)
end
```
Reason: Local SQLite is typically lower latency because it avoids remote MySQL network round trips and separate database-server overhead for a single-server data store.


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

local function CachedSteamID(ply)
    local steamID = steamIDCache[ply]
    if steamID ~= nil then
        return steamID
    end

    if not isValid(ply) then
        return nil
    end

    steamID = ply:SteamID()
    steamIDCache[ply] = steamID
    return steamID
end

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

-- Hot path: call once per player, then reuse the local string.
local function ProcessPlayers(players)
    for i = 1, #players do
        local ply = players[i]
        local steamID = CachedSteamID(ply)

        if steamID ~= nil then
            -- Use steamID here instead of calling ply:SteamID() again.
        end
    end
end
```
Reason: Cache the immutable SteamID per Player entity, avoid repeated engine method calls in the hot loop, and clear entries when players disconnect.


```lua
-- Slower: repeatedly copies the growing string.
local slow = ""
for i = 1, 10000 do
    slow = slow .. "piece " .. i .. "\n"
end

-- Faster: collect pieces, then join once.
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece " .. i .. "\n"
end

local fast = table.concat(parts)
```
Reason: `table.concat` joins all pieces in one pass, while repeated `..` keeps reallocating and copying the growing string.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect avoids draw.RoundedBox's wrapper/rounded-corner overhead when radius is 0.


```lua
local text = "Single line"
local font = "DermaDefault"
local x, y = 32, 32

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.DrawText` does the direct single-line draw work, avoiding `draw.DrawText` multiline/layout overhead and `SimpleTextOutlined` extra outline draws.


```lua
local length = #arrayLikeTable
```
Reason: `#` is the preferred length operator for sequential array-like tables; `table.Count` is for counting keyed entries.


```lua
t = {}
```
Reason: Rebinding is generally faster for large sequential tables because it avoids walking every element; use table.Empty(t) only when other references must keep seeing the same table.


```lua
-- Slower: scans the whole list
local allowedList = { "weapon_pistol", "weapon_smg1", "weapon_crowbar" }
if table.HasValue(allowedList, weaponClass) then
    -- allowed
end

-- Faster: use a set-style table
local allowedSet = {
    weapon_pistol = true,
    weapon_smg1 = true,
    weapon_crowbar = true,
}

if allowedSet[weaponClass] then
    -- allowed
end
```
Reason: A set table uses direct key lookup, while table.HasValue scans the list every time.


```lua
local data = {
    id = id,
    name = name,
    score = score,
}
```
Reason: The table constructor creates and fills the known fields in one step, avoiding the extra empty-table creation plus later field assignments.


```lua
local item = items[math.random(#items)]
```
Reason: For a non-empty sequential table, `#items` plus numeric indexing is O(1), while `table.Random` handles arbitrary keyed tables and does extra traversal work.


```lua
local squared = x * x
```
Reason: Multiplication is the preferred fast form for squaring in a tight Lua loop; it avoids exponentiation overhead.


```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` visits connected players directly without creating the `player.GetAll()` table first.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent
    end
end
```
Reason: `ents.Iterator()` streams entities one by one, so it avoids materializing a full table like `ents.GetAll()` before filtering by class.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a callback for the `Think` hook, and `MyAddon.Think` is the unique identifier for that registration.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that the entity reference exists and has not been removed, so method calls are safe behind that guard.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` registers the callback for the named incoming net message on the receiving side.


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

-- Hot path: reuse the shared zero angle instead of allocating a new one.
entity:SetAngles(ZERO_ANGLE)

-- Slower in a hot path:
-- entity:SetAngles(Angle(0, 0, 0))
```
Reason: Reusing one cached zero `Angle` avoids repeated object allocation and constructor overhead in the hot path.


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

local color = MYADDON_COLOR
```
Reason: A flat local is faster to read because it avoids repeated table lookups and benefits from Lua's cheapest variable access path.


```lua
local jobName = team.GetName(ply:Team())
-- instead of: local jobName = ply:GetNWString("job")
```
Reason: `team.GetName(ply:Team())` is the canonical DarkRP/GMod source of a player’s current job name, while `GetNWString("job")` depends on networked state and is less reliable as an API contract.


```lua
if pos1:DistToSqr(pos2) <= (radius * radius) then
    -- within radius
end
```
Reason: `Vector:DistToSqr` avoids the square root work of `Distance` when you only need a threshold comparison, so it is the preferred faster check.


Answer must contain 1 through 1 candidate loops.

```lua
if ents.Iterator then
    for ent in ents.Iterator() do
        -- use ent
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- use ent
    end
end
```
Reason: `ents.Iterator()` avoids building the full entity table and is the preferred efficient iterator when available; `ipairs(ents.GetAll())` is the compatible fallback.


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

for i = 1, #nearby do
    local ent = nearby[i]
    -- use ent
end
```
Reason: `ents.FindInSphere` is a common fast built-in default for cheap nearby-entity queries without relying on PVS visibility state.


```lua
local player_GetAll = player.GetAll
local DistToSqr = FindMetaTable("Vector").DistToSqr

local function FindPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local playersInRange = {}

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

    return playersInRange
end
```
Reason: Iterating `player.GetAll()` avoids the broad entity-sphere search and class filtering overhead of `ents.FindInSphere`, and squared-distance checks avoid the extra square root cost.


```lua
for i = 1, n do
    -- body
end
```
Reason: Numeric `for` is generally faster for tight 1..n counting loops in Garry's Mod Lua because it uses the VM's specialized loop primitive with less per-iteration overhead than an equivalent `while`.


Answer must contain 0 through 1 candidate loops.

```lua
local players = player.GetHumans()

-- Faster: one hook dispatch, handlers loop players internally.
hook.Run("MyPlayersTick", players)

hook.Add("MyPlayersTick", "CustomLogic", function(playersList)
    for i = 1, #playersList do
        local ply = playersList[i]
        if not IsValid(ply) then continue end

        -- per-player custom logic here
    end
end)

-- Slower pattern:
for i = 1, #players do
    hook.Run("MyPlayerTick", players[i])
end
```
Reason: One `hook.Run` avoids repeated hook-system dispatch, argument setup, and lookup work every tick; looping players inside the handler is cheaper than re-entering the hook system per player.


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

draw.SimpleText(hp, "DermaLarge", x1, y1, color_white)
draw.RoundedBox(4, x2, y2, math.max(hp, 0) * 2, 20, color_green)
draw.SimpleText(hp .. "%", "Trebuchet24", x3, y3, color_white)
```
Reason: Cache `LocalPlayer():Health()` in a local once per frame so the three draw calls reuse one value instead of making the same engine call three times.


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

function PANEL:Paint(w, h)
    surface.SetDrawColor(COLOR_WHITE)
    surface.DrawRect(0, 0, w, h)
end
```
Reason: Reusing one `Color` object avoids per-frame allocation and constructor overhead inside the paint loop.


```lua
local sin = math.sin

for i = 1, n do
    local y = sin(i)
    -- hot path work
end
```
Reason: Caching `math.sin` in a local avoids repeated table/global lookups inside the loop, which is a small but common Lua hot-path optimization.


```lua
local cachedPly

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

hook.Add("Think", "UseCachedLocalPlayer", function()
    local ply = cachedPly
    if not IsValid(ply) then
        ply = LocalPlayer()
        if not IsValid(ply) then return end
        cachedPly = ply
    end

    local pos = ply:GetPos()
    -- use ply repeatedly here instead of calling LocalPlayer() again
end)
```
Reason: Cache the player entity once and reuse a local variable in hot paths, so you avoid repeated global function lookup and repeated `LocalPlayer()` calls while still refreshing if the cached entity becomes invalid.


```lua
local COS_45 = 0.70710678 -- cos(45 deg), tune threshold as needed

local function RoughlyLookingAtEachOther(plyA, plyB)
    local a = plyA:GetAimVector()
    local b = plyB:GetAimVector()

    -- Dot product near -1 means the aim directions face each other.
    return a:Dot(b) <= -COS_45
end
```
Reason: A dot product is much cheaper than `math.acos`; comparing `a:Dot(b)` against a cosine threshold avoids angle conversion while still giving a fast rough facing test.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally a bit faster for a helper you control because it can call a plain/local function directly, while `ply:SomeHelper()` adds a method lookup before passing `self`.


```lua
MsgN("[debug] velocity=", velocity, " state=", state)
```
Reason: `MsgN` is a lighter console write path than `print` in Garry's Mod, so it avoids extra formatting overhead in hot code.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: A numeric `for` over a dense sequential table avoids the iterator overhead of `pairs` and `ipairs`, so it is the fastest typical choice in Garry's Mod Lua for array-like numeric data.


```lua
local players = player.GetAll()
local result = {}
local n = 0

for i = 1, #players do
    local ply = players[i]
    if IsValid(ply) and ply:Alive() and ply:isCP() then
        n = n + 1
        result[n] = ply:Nick()
    end
end

return result
```
Reason: A single plain Lua loop avoids DarkRP fn combinator call overhead, extra closures, and intermediate tables while doing the same filter+map work in one pass.


```lua
local activePlayers = {}

local function refreshActivePlayers()
    activePlayers = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "RefreshActivePlayersJoin", refreshActivePlayers)
hook.Add("PlayerDisconnected", "RefreshActivePlayersLeave", refreshActivePlayers)

refreshActivePlayers()

hook.Add("Tick", "UseCachedPlayers", function()
    for i = 1, #activePlayers do
        local ply = activePlayers[i]
        if IsValid(ply) then
            -- per-player tick work here
        end
    end
end)
```
Reason: `player.GetAll()` allocates and walks the player list each tick; caching moves that cost to join/leave events so the hot Tick path only iterates the current table.


```lua
local cachedScore = {}

local function SetCachedScore(ply, value)
    cachedScore[ply:EntIndex()] = value
end

local function GetCachedScore(ply)
    return cachedScore[ply:EntIndex()]
end

hook.Add("PlayerDisconnected", "ClearCachedScore", function(ply)
    cachedScore[ply:EntIndex()] = nil
end)
```
Reason: Array-style lookup through a local Lua table keyed by `ply:EntIndex()` avoids the player userdata/metatable field access path, so hot reads are typically faster than `ply.someField`.


```lua
local values = { "alpha", "beta", "gamma", "delta" }

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays are faster to iterate because Lua stores and traverses the array part more efficiently than string-keyed hash maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw RGBA numbers avoids the extra table/object access from a `Color` value, so it is the faster style in a hot draw path.


```lua
local result = sql.Query("SELECT money FROM players WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: Local SQLite via Garry's Mod `sql` library is typically lower latency on a single server because it avoids network round trips and remote database overhead.


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

local function GetSteamIDCached(ply)
    local steamId = steamIdCache[ply]
    if steamId ~= nil then
        return steamId
    end

    steamId = ply:SteamID()
    steamIdCache[ply] = steamId
    return steamId
end

hook.Add("EntityRemoved", "ClearSteamIDCache", function(ent)
    steamIdCache[ent] = nil
end)

-- hot path
local function HandlePlayer(ply)
    local steamId = GetSteamIDCached(ply)
    -- use steamId repeatedly here
end
```
Reason: Cache the per-player SteamID once and reuse it, avoiding repeated Lua-to-engine calls on the hot path while weak keys prevent stale player references from being kept alive.


```lua
local parts = {}

for i = 1, 10000 do
    parts[i] = "piece_" .. i
end

local big = table.concat(parts)
print(big)
```
Reason: `table.concat` is faster because repeated `..` rebuilds and copies the growing string on each append, while `table.concat` joins all pieces in one pass.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids the extra `draw.RoundedBox` wrapper work, so for plain non-rounded rectangles it is slightly faster.


```lua
-- Fast path for drawing the same single-line string each frame.
-- Lower-level surface text calls avoid the extra work in draw.DrawText / draw.SimpleTextOutlined.

local font = "DermaLarge"
local text = "Speed"
local x, y = 100, 80
local r, g, b, a = 255, 255, 255, 255

surface.CreateFont("BenchFastText", {
    font = "Tahoma",
    size = 24,
    weight = 500,
    antialias = true,
})

hook.Add("HUDPaint", "BenchFastText", function()
    surface.SetFont("BenchFastText")
    surface.SetTextColor(r, g, b, a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the leaner hot-path for single-line text; `draw.DrawText` adds wrapping/alignment handling and `draw.SimpleTextOutlined` adds extra outline passes.


```lua
local len = #tbl
```
Reason: `#` is the idiomatic and preferred way to get the length of a sequential array-like table in Garry's Mod Lua.


```lua
local t = {}
```
Reason: Rebinding with `t = {}` is generally faster because it avoids iterating and clearing every existing array slot like `table.Empty(t)` does; use `table.Empty(t)` only when other references must keep the same table object.


```lua
-- Slow on a list: table.HasValue(allowed, value)

local allowed = {
    foo = true,
    bar = true,
    baz = true,
}

if allowed[value] then
    -- value exists in the set
end
```
Reason: A keyed lookup is O(1) on average, while `table.HasValue` scans the list linearly with O(n) cost.


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

-- Slower:
-- local t = {}
-- t.x = 1
-- t.y = 2
-- t.z = 3
```
Reason: For a small table with known keys, the table constructor is faster because it builds and populates the table in one step instead of doing multiple separate field assignments.


```lua
local n = #t
local value = n > 0 and t[math.random(n)] or nil
```
Reason: For a sequential table, direct indexed lookup with `math.random(#t)` avoids the extra key collection and branching overhead of `table.Random`.


```lua
local x2 = x * x
```
Reason: `x * x` is the direct arithmetic operation and avoids the extra overhead of generic power helpers in a tight loop.


```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` iterates connected players directly without allocating the table from `player.GetAll()`.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one by one, so filtering by class avoids allocating a full table like `ents.FindByClass("prop_physics")` would.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a function on Garry's Mod's `Think` hook, and `MyAddon.Think` is the unique identifier for that callback.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that rejects `nil`, invalid entity handles, and removed entities before you call methods on them.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` registers the callback that Garry's Mod runs whenever the `MyAddon.Sync` net message arrives.


```lua
local scratchAng = Angle()

local function GetScratchZeroAngle()
    scratchAng.p = 0
    scratchAng.y = 0
    scratchAng.r = 0
    return scratchAng
end

-- slower in a hot path:
-- local ang = Angle()

-- faster in a hot path:
local ang = GetScratchZeroAngle()
```
Reason: Reusing one preallocated `Angle` and zeroing its fields avoids repeated allocation and GC work, which is cheaper on hot paths than constructing `Angle()` every time.


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

local color = MYADDON_COLOR
```
Reason: A flat local is faster for frequent reads because it avoids repeated table lookups and uses Lua's cheapest variable access path.


```lua
local teamData = RPExtraTeams[ply:Team()]
local jobName = teamData and teamData.name or team.GetName(ply:Team())
```
Reason: DarkRP stores the authoritative job on the player's team, so `ply:Team()` with `RPExtraTeams` or `team.GetName` is the supported path; `GetNWString("job")` is legacy networked state that can be missing, stale, or gamemode-dependent.


```lua
if pos1:DistToSqr(pos2) <= (radius * radius) then
    -- within radius
end
```
Reason: `Vector:DistToSqr` avoids the expensive square root used by real distance and is the preferred method for threshold comparisons.


```lua
local iter = ents.Iterator and ents.Iterator() or ipairs(ents.GetAll())

for _, ent in iter do
    -- use ent
end
```
Reason: `ents.Iterator()` avoids building a full entity table and is the efficient wiki-recommended choice; the fallback keeps the loop working where that iterator is unavailable.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a common fast built-in default for cheap nearby-entity queries, using direct radius filtering without the broader visibility semantics and extra noise of `FindInPVS`.


```lua
local player_GetAll = player.GetAll

local function FindPlayersNear(pos, radius)
    local players = player_GetAll()
    local result = {}
    local radiusSqr = radius * radius
    local count = 0

    for i = 1, #players do
        local ply = players[i]

        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            count = count + 1
            result[count] = ply
        end
    end

    return result
end
```
Reason: Iterating `player.GetAll()` and comparing squared distance avoids scanning every entity and avoids the extra player-filter pass, which is usually much cheaper on busy servers.


```lua
for i = 1, n do
    -- hot loop body
end
```
Reason: Numeric `for` is generally faster for tight 1..n counting in Garry's Mod Lua because the loop control is built in and avoids the extra increment/check work of a manual `while` loop.


```lua
-- Faster: one hook dispatch per tick, pass all players to listeners.
hook.Add("Tick", "NotifyCustomLogic", function()
    local players = player.GetAll()
    hook.Run("MyPlayersTick", players)
end)

-- Slower: repeated hook dispatch for every player each tick.
hook.Add("Tick", "NotifyCustomLogic_Slower", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("MyPlayerTick", ply)
    end
end)
```
Reason: Calling `hook.Run` once avoids per-player hook dispatch overhead, table lookups, and vararg/setup costs every tick.


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

    draw.SimpleText(hp, "DermaLarge", 32, 32, color_white)
    draw.RoundedBox(4, 32, 72, hp * 2, 20, Color(200, 50, 50))
    draw.SimpleText(hp .. "%", "DermaDefaultBold", 32, 100, color_white)
end)
```
Reason: Cache `LocalPlayer():Health()` once per frame to avoid three repeated Lua/C++ calls in the same `HUDPaint` pass.


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

hook.Add("HUDPaint", "FastPaintExample", function()
    for i = 1, itemCount do
        surface.SetDrawColor(COLOR_WHITE)
        -- draw work here
    end
end)
```
Reason: Reusing one cached `Color` avoids per-iteration allocation and function-call overhead in the hot paint loop.


```lua
local sin = math.sin

for i = 1, n do
    out[i] = sin(i * step)
end
```
Reason: Caching `math.sin` in a local avoids repeated global/table lookups inside the hot loop, which is slightly faster in Lua.


```lua
local lp

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

hook.Add("Think", "UseCachedLocalPlayer", function()
    if not IsValid(lp) then
        lp = LocalPlayer()
        if not IsValid(lp) then return end
    end

    local pos = lp:GetPos()
    local vel = lp:GetVelocity()

    -- use pos / vel / lp here
end)
```
Reason: Cache the `LocalPlayer()` result and refresh only when needed so hot-path code reuses one local reference instead of repeating a global function lookup and player resolution every time.


```lua
local function PlayersRoughlyLookingAtEachOther(plyA, plyB, minFacingDot)
    minFacingDot = minFacingDot or 0.8 -- ~36.9 degrees tolerance

    local a = plyA:GetAimVector()
    local b = plyB:GetAimVector()

    -- If aim directions face each other, their normalized vectors point in opposite directions.
    return a:Dot(b) <= -minFacingDot
end
```
Reason: `GetAimVector()` is already normalized, so a single dot-product threshold avoids `math.acos` and gives a cheap facing check based on whether the two aim directions point roughly opposite each other.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally the better choice for a helper you control because it avoids the extra table field method lookup and communicates that this is a plain helper, not object state/behavior on `ply`.


```lua
MsgN("hot path debug")
```
Reason: `MsgN` writes directly to the console with less overhead than `print`, making it a better fit for hot-path debug output.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: `numeric for` is the typical fastest choice for a large dense array because it avoids the extra iterator machinery of `pairs`/`ipairs` and indexes the sequential part directly.


```lua
-- Faster than DarkRP's fn.Filter(...):Map(...) style by doing one pass,
-- avoiding closure/combinator overhead and intermediate tables.
local players = player.GetAll()
local result = {}
local out = 1

for i = 1, #players do
    local ply = players[i]

    if IsValid(ply) and ply:Team() == TEAM_POLICE and ply:Alive() then
        result[out] = ply:Nick()
        out = out + 1
    end
end

return result
```
Reason: A single hand-written loop is faster because it fuses filter and map into one pass, avoids extra function calls/closures from `fn`, and does not allocate intermediate lists.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "MyAddon.RefreshPlayerCache", refreshPlayers)
hook.Add("PlayerDisconnected", "MyAddon.RefreshPlayerCache", refreshPlayers)
hook.Add("InitPostEntity", "MyAddon.RefreshPlayerCache", refreshPlayers)

hook.Add("Think", "MyAddon.FastPlayerLoop", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- per-player work here
        end
    end
end)
```
Reason: `player.GetAll()` allocates and walks the full player list every tick, so caching removes repeated table creation and only rebuilds the list when membership changes.


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

local function SetTempValue(ply, value)
    local slot = playerData[ply]
    if slot == nil then
        slot = {}
        playerData[ply] = slot
    end

    slot.someField = value
end

local function GetTempValue(ply)
    local slot = playerData[ply]
    return slot and slot.someField or nil
end

hook.Add("PlayerDisconnected", "CleanupTempValue", function(ply)
    playerData[ply] = nil
end)
```
Reason: A plain side-table lookup avoids hitting the player entity table/metatable path on every read, and weak keys keep temporary per-player state cheap to read and easy to clean up.


```lua
local values = { "alpha", "beta", "gamma", "delta" }

for i = 1, #values do
    local v = values[i]
    -- use v
end
```
Reason: Sequential number-indexed arrays iterate faster in Garry's Mod Lua because they use the table's array part with simpler numeric access, while string-keyed maps require hash lookup.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw numeric RGBA avoids the extra table/object access and is the faster style for a hot draw path.


```lua
local row = sql.QueryRow("SELECT coins FROM players WHERE steamid = " .. sql.SQLStr(steamId))
if row then
    local coins = tonumber(row.coins) or 0
end
```
Reason: For one Garry's Mod server with no cross-server sync, local SQLite is typically lower latency because it avoids network round trips and remote database overhead.


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

local function GetSteamIDCached(ply)
    local steamId = steamIdCache[ply]
    if steamId ~= nil then
        return steamId
    end

    steamId = ply:SteamID()
    steamIdCache[ply] = steamId
    return steamId
end

hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIdCache[ply] = nil
end)

-- hot path
local function DoWork(players)
    for i = 1, #players do
        local ply = players[i]
        local steamId = GetSteamIDCached(ply)
        -- use steamId
    end
end
```
Reason: It computes `ply:SteamID()` once per player and reuses the stored string on the hot path, avoiding repeated method calls and allocations while letting weak keys and disconnect cleanup release stale entries.


```lua
local parts = {}
for i = 1, 10000 do
    parts[i] = "piece" .. i
end

local big = table.concat(parts)
```
Reason: `table.concat` is faster because repeated `..` rebuilds and copies the growing string on each append, while `table.concat` joins all pieces in one pass.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` avoids `draw.RoundedBox`'s extra wrapper and corner logic, so it is slightly faster for plain non-rounded rectangles.


```lua
local font = "BudgetLabel"
local text = "FPS: 144"
local x, y = 24, 24
local color_white = Color(255, 255, 255)

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(color_white)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextColor` + `surface.SetTextPos` + `surface.DrawText` is the leanest path for one single-line string each frame; `draw.DrawText` adds wrapping/alignment handling you do not need, and `draw.SimpleTextOutlined` is slower again because it performs extra outline draws.


```lua
local len = #tbl
```
Reason: `#` is the idiomatic and fastest way to get the length of a contiguous 1-based array-like table in Garry's Mod Lua.


```lua
-- Faster when you can replace the table reference.
t = {}
```
Reason: `t = {}` is generally faster because it creates a new table in constant time, while `table.Empty(t)` walks and clears the existing array/hash contents, which is proportional to the table size.


```lua
local allowed = {
    foo = true,
    bar = true,
    baz = true,
}

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

-- Slower list scan:
-- if table.HasValue({ "foo", "bar", "baz" }, value) then ... end
```
Reason: `allowed[value]` is a direct hash-table lookup, while `table.HasValue` scans the list linearly and gets slower as the list grows.


```lua
-- Faster: put known fields directly in the constructor
local t = {
    x = 1,
    y = 2,
    z = 3,
}

-- Slower: create empty table, then assign each field
local u = {}
u.x = 1
u.y = 2
u.z = 3
```
Reason: For a small table with known fields, the table constructor is faster because it creates and initializes the table in one step, avoiding multiple separate field assignment operations.


```lua
local value = list[math.random(#list)]
```
Reason: For a sequential table, direct indexed access avoids `table.Random`'s extra work for generic tables and uses the array length in O(1).


```lua
local y = x * x
```
Reason: `x * x` avoids the exponent operator overhead and is the preferred fast form in a tight loop.


```lua
for _, ply in player.Iterator() do
    -- your code here
end
```
Reason: `player.Iterator()` iterates connected players directly without allocating the table returned by `player.GetAll()`.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` streams entities one by one, so it avoids materializing a full table like `ents.GetAll()` or `ents.FindByClass()` first.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- per-frame logic here
end)
```
Reason: `hook.Add` registers a function on Garry's Mod's `Think` hook under the identifier `MyAddon.Think`, so it runs every think tick.


```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```
Reason: `IsValid(ent)` checks that the reference exists and the entity has not been removed, which is the standard safe guard before calling entity methods in Garry's Mod Lua.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here.
end)
```
Reason: `net.Receive` registers the server/client-side callback that runs when a `MyAddon.Sync` net message arrives.


```lua
-- Slower in a hot path:
-- local ang = Angle()

local scratchAng = Angle()

local function getZeroedAngleScratch()
    scratchAng:SetUnpacked(0, 0, 0)
    return scratchAng
end
```
Reason: Reusing a preallocated `Angle` and zeroing it avoids per-call allocation and GC, which is faster than constructing `Angle()` every time.


```lua
local MYADDON_COLOR = myaddon.config.color
local color = MYADDON_COLOR
```
Reason: A local variable is fastest to read in Lua; `myaddon.config.color` does table lookups each access, and a global is also slower than a local.


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

-- Avoid relying on the raw NWString directly
local oldJobName = ply:GetNWString("job")
```
Reason: `ply:getDarkRPVar("job")` is DarkRP’s intended abstraction for DarkRP-owned player state, so it is clearer, more compatible with DarkRP internals, and less brittle than reading the underlying networked string directly.


```lua
local maxDistance = 300

if vecA:DistToSqr(vecB) <= maxDistance * maxDistance then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root from `Distance`, so it is the preferred method for faster threshold-only comparisons.


```lua
if ents.Iterator then
    for _, ent in ents.Iterator() do
        -- use ent
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- fallback for older environments
    end
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient way to visit every entity, and the fallback keeps the code working where that iterator is unavailable.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) and ent ~= ply then
        -- use ent
    end
end
```
Reason: `ents.FindInSphere` is a common fast default for “near player” queries in server Lua benchmarks because it directly matches a radial proximity check without the heavier visibility-oriented cost of `FindInPVS`.


```lua
local function FindPlayersInRadius(pos, radius, out)
    out = out or {}

    local count = 0
    local radiusSqr = radius * radius
    local players = player.GetAll()

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

    for i = count + 1, #out do
        out[i] = nil
    end

    return out
end
```
Reason: This only scans players instead of every entity and uses squared-distance checks to avoid the extra entity search and square-root work.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric `for` is generally faster for tight 1..n counting in Garry's Mod Lua because the counter and limit handling are built into the VM, avoiding the extra increment and condition work of a manual `while` loop.


```lua
-- Faster: one hook dispatch per tick, handlers loop players internally.
hook.Add("Tick", "MyPerTickNotifier", function()
    hook.Run("MyPlayersTick", player.GetAll())
end)

hook.Add("MyPlayersTick", "MyCustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- per-player custom logic here
    end
end)

-- Slower: repeated hook dispatch per player every tick.
hook.Add("Tick", "MyPerPlayerNotifier", function()
    local players = player.GetAll()
    for i = 1, #players do
        hook.Run("MyPlayerTick", players[i])
    end
end)
```
Reason: Calling `hook.Run` once avoids repeated hook table lookup, vararg packing, and callback dispatch per player, so the per-player loop should live inside the hook handler instead.


```lua
hook.Add("HUDPaint", "DrawHealth", function()
    local lp = LocalPlayer()
    local health = lp:Health()

    draw.SimpleText(health, "Trebuchet24", 20, 20, color_white)
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(20, 50, health * 2, 16)
    draw.SimpleText(health .. "%", "Trebuchet18", 20, 72, color_white)
end)
```
Reason: it avoids repeating `LocalPlayer()` and `:Health()` lookups in the same frame by caching the value once and reusing it for all three draws.


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

hook.Add("HUDPaint", "MyFastPaint", function()
    surface.SetDrawColor(WHITE)

    for i = 1, 1000 do
        surface.DrawRect(i, i, 4, 4)
    end
end)
```
Reason: Reusing one prebuilt `Color` avoids allocating and initializing a new table every loop iteration.


```lua
local sin = math.sin

for i = 1, n do
    local y = sin(i * 0.1)
    -- hot loop work
end
```
Reason: Caching `math.sin` in a local avoids repeated table lookups on `math` inside the hot loop.


```lua
local LocalPlayer = LocalPlayer
local lp

local function GetLocalPlayerCached()
    if not IsValid(lp) then
        lp = LocalPlayer()
    end

    return lp
end

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

    local hp = ply:Health()
    local armor = ply:Armor()
    -- use ply, hp, armor here
end)
```
Reason: This localizes the global `LocalPlayer` lookup and reuses the resolved player entity, so hot code paths avoid repeated global table lookups and repeated `LocalPlayer()` calls.


```lua
local function AreAimDirectionsFacingEachOther(plyA, plyB, minOpposedDot)
    minOpposedDot = minOpposedDot or 0.8 -- about 37 degrees from perfectly opposite

    local dot = plyA:GetAimVector():Dot(plyB:GetAimVector())
    return dot <= -minOpposedDot
end
```
Reason: `GetAimVector()` is already normalized, so one dot product gives a cheap cosine-space test; values near `-1` mean the players' aim directions are facing each other, with no `math.acos` cost.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally the faster and better default for a helper you control because it avoids method-style lookup on `ply`/its metatable and can stay a local function.


```lua
MsgN("[debug] hot path hit: ", entIndex, " frame=", FrameNumber())
```
Reason: `MsgN` is cheaper than `print` in Garry's Mod because it writes directly to the console with less formatting overhead, so it is better for hot paths.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: Numeric `for` is typically fastest for large dense arrays in Garry's Mod Lua because it does direct indexed access and avoids the extra iterator overhead of `pairs` and `ipairs`.


```lua
local playerGetAll = player.GetAll

local function aliveCitizenNames()
    local players = playerGetAll()
    local out = {}
    local n = 0

    for i = 1, #players do
        local ply = players[i]
        if IsValid(ply) and ply:Alive() and ply:getDarkRPVar("job") == "Citizen" then
            n = n + 1
            out[n] = ply:Nick():upper()
        end
    end

    return out
end
```
Reason: A single indexed loop is faster than DarkRP `fn` filter/map chains because it avoids extra function calls, closures, and intermediate tables while doing the same transform in one pass.


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

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

hook.Add("PlayerInitialSpawn", "MyAddon.RefreshPlayerCache", function()
    RefreshPlayerCache()
end)

hook.Add("PlayerDisconnected", "MyAddon.RefreshPlayerCache", function()
    RefreshPlayerCache()
end)

hook.Add("Tick", "MyAddon.FastPlayerLoop", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- per-player tick work here
        end
    end
end)
```
Reason: `player.GetAll()` allocates and walks the full player list every tick; caching moves that cost to join/leave events and keeps the hot `Tick` path to a tight indexed loop.


```lua
local hotDataByPlayerId = {}

local function SetHotData(ply, value)
    hotDataByPlayerId[ply:EntIndex()] = value
end

local function GetHotData(ply)
    return hotDataByPlayerId[ply:EntIndex()]
end

hook.Add("PlayerDisconnected", "ClearHotData", function(ply)
    hotDataByPlayerId[ply:EntIndex()] = nil
end)
```
Reason: A plain Lua table keyed by `ply:EntIndex()` avoids userdata/metatable field access on `ply.someField`, so repeated reads are cheaper in hot paths.


```lua
local values = {
    "alpha",
    "beta",
    "gamma",
    "delta",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays are faster to iterate because Lua stores dense integer keys in the array part and a numeric `for` loop avoids the hash-table work of string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing raw `r, g, b, a` numbers avoids the extra table/object access of a `Color` value, so it is the faster call style in a hot draw path.


```lua
local rows = sql.Query("SELECT money FROM players WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: Local SQLite via Garry's Mod `sql` library is typically lower latency on a single server because it avoids network round trips and remote database overhead.


```lua
local PLAYER = FindMetaTable("Player")

local function GetCachedSteamID(ply)
    local sid = ply._cachedSteamID
    if sid ~= nil then
        return sid
    end

    sid = PLAYER.SteamID(ply)
    ply._cachedSteamID = sid
    return sid
end

hook.Add("PlayerDisconnected", "ClearCachedSteamID", function(ply)
    ply._cachedSteamID = nil
end)

-- hot path
for i = 1, #players do
    local ply = players[i]
    local sid = GetCachedSteamID(ply)
    -- use sid
end
```
Reason: It turns repeated `ply:SteamID()` calls into one call per player and then reuses a cheap Lua field lookup on the hot path.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "part" .. i
end

-- Slow: repeated string reallocation/copying
local slow = ""
for i = 1, #pieces do
    slow = slow .. pieces[i]
end

-- Fast: collect pieces, join once
local fastParts = {}
for i = 1, #pieces do
    fastParts[i] = pieces[i]
end
local fast = table.concat(fastParts)
```
Reason: `table.concat` is faster because it joins all pieces in one pass instead of reallocating and copying the whole string on every `..` append.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` adds wrapper overhead, while `surface.SetDrawColor` + `surface.DrawRect` is the direct non-rounded rectangle path and is slightly faster when called many times per frame.


```lua
local font = "Trebuchet24"
local text = "FPS: 144"
local x, y = 32, 32
local r, g, b, a = 255, 255, 255, 255

hook.Add("HUDPaint", "FastSingleLineText", function()
    surface.SetFont(font)
    surface.SetTextColor(r, g, b, a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the leanest path for a single-line string; `draw.DrawText` adds wrapping/alignment work and `draw.SimpleTextOutlined` adds extra outline passes.


```lua
local len = #tbl
```
Reason: `#` is the preferred fast way to get the length of a sequential array-like table; `table.Count` is for counting all keys in non-sequential tables.


```lua
-- Generally faster for repeatedly discarding a large sequential table:
t = {}
```
Reason: `t = {}` usually avoids walking and niling every existing element like `table.Empty(t)` does, so it is generally faster for large array-like tables when you do not need to preserve the same table reference.


```lua
local allowed = {
    pistol = true,
    shotgun = true,
    smg1 = true,
}

if allowed[value] then
    -- value exists in the set
end
```
Reason: `table.HasValue` scans a list linearly, while a keyed lookup table uses direct key access and is much faster for repeated membership checks.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: For a small table with known fields, the table constructor is faster because it creates and fills the table in one step instead of doing extra writes after `{}`.


```lua
local t = {"a", "b", "c", "d"}
local v = t[math.random(#t)]
```
Reason: For a sequential table, direct array indexing with `math.random(#t)` avoids the extra work `table.Random` does for non-array keys and is therefore faster.


```lua
local y = x * x
```
Reason: `x * x` is the fastest common form in a tight Lua loop because it uses direct multiplication and avoids the extra overhead of exponentiation like `x ^ 2`.


```lua
for _, ply in player.Iterator() do
    -- ...
end
```
Reason: `player.Iterator()` iterates the currently connected players directly without first building a `player.GetAll()` table.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- use ent here
    end
end
```
Reason: `ents.Iterator()` yields entities one at a time, so it does not build a full entity table like `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- per-frame logic here
end)
```
Reason: `hook.Add` registers a function on Garry's Mod's `Think` hook, and `MyAddon.Think` is the unique identifier for that callback.


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

ent:SomeMethod()
```
Reason: `IsValid(ent)` is the standard Garry's Mod guard for entity references and rejects `nil`, `NULL`, and removed/invalid entities before you call methods on them.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming sync message here.
end)
```
Reason: `net.Receive` registers a callback for the named incoming net message, so this handler runs whenever `MyAddon.Sync` is received.


```lua
local scratchAng = Angle()

-- Slow in a hot path:
-- local ang = Angle()

-- Fast when the value is scratch-only for immediate use:
local function getZeroAngle()
    scratchAng.p = 0
    scratchAng.y = 0
    scratchAng.r = 0
    return scratchAng
end
```
Reason: Reusing one scratch `Angle` and zeroing it in place avoids per-call allocation and garbage collection overhead; only use it when callers do not retain the returned object.


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

local color = MYADDON_COLOR
```
Reason: A local variable is fastest for hot reads because Lua resolves locals directly, while `myaddon.config.color` does multiple table lookups and globals also require an environment lookup.


```lua
-- Preferred in DarkRP
local jobName = ply:getDarkRPVar("job") or ""

-- Avoid for DarkRP job data
local oldJobName = ply:GetNWString("job")
```
Reason: `job` is a DarkRPVar, so `ply:getDarkRPVar("job")` is the framework API DarkRP maintains and syncs correctly; `GetNWString("job")` bypasses that contract.


```lua
local maxDist = 256

if pos1:DistToSqr(pos2) <= maxDist * maxDist then
    -- within range
end
```
Reason: `Vector:DistToSqr` avoids the square root in `Distance`, so it is the preferred faster check when you only need to compare against a threshold.


```lua
if ents.Iterator then
    for _, ent in ents.Iterator() do
        -- Work with ent here
    end
else
    for _, ent in ipairs(ents.GetAll()) do
        -- Work with ent here
    end
end
```
Reason: `ents.Iterator()` avoids building a full entity table and is the efficient wiki-recommended choice when you only need to visit every entity.


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

for i = 1, #nearby do
    local ent = nearby[i]
    if ent ~= ply and IsValid(ent) then
        -- cheap nearby-entity work here
    end
end
```
Reason: `ents.FindInSphere` is a common fast built-in spatial query for “near player” checks, usually benchmarking well among general-purpose `FindIn*` options without depending on PVS visibility state.


```lua
local player_GetAll = player.GetAll
local table_Empty = table.Empty

local function FindPlayersNear(pos, radius, out)
    out = out or {}
    table_Empty(out)

    local players = player_GetAll()
    local radiusSqr = radius * radius
    local n = 0

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

    return out
end
```
Reason: It scans only the player list instead of all entities in the sphere, uses squared distance to avoid extra math, and can reuse the output table to reduce allocations on hot paths.


```lua
for i = 1, n do
    -- body
end
```
Reason: Numeric `for` is generally faster for tight 1..n counting in Garry's Mod Lua because the runtime handles the loop counter and bounds more efficiently than a manual `while` loop.


```lua
-- Faster: dispatch one hook per tick and pass the player list once.
hook.Add("Tick", "NotifyPlayersFast", function()
    local players = player.GetAll()
    hook.Run("MyPlayersTick", players)
end)

-- Example consumer for the fast pattern.
hook.Add("MyPlayersTick", "CustomLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- custom logic for ply
    end
end)

-- Slower: dispatch one hook per player per tick.
hook.Add("Tick", "NotifyPlayersSlow", function()
    local players = player.GetAll()

    for i = 1, #players do
        hook.Run("MyPlayerTick", players[i])
    end
end)
```
Reason: Calling `hook.Run` once avoids repeated hook dispatch, argument setup, and lookup overhead every tick, so it scales better as player count rises.


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

    local health = ply:Health()
    local healthText = tostring(health)

    draw.SimpleText(healthText, "Trebuchet24", 32, 32, color_white)
    draw.RoundedBox(4, 32, 64, math.Clamp(health, 0, 100) * 2, 20, Color(220, 60, 60))
    draw.SimpleText(healthText, "Trebuchet18", 240, 66, color_white)
end)
```
Reason: It reads `LocalPlayer():Health()` once per frame and reuses the cached value, avoiding repeated Lua-to-engine calls and extra string conversion work.


```lua
local WHITE = color_white -- reuse; do not mutate

function PANEL:Paint(w, h)
    surface.SetDrawColor(WHITE)

    for i = 1, 100 do
        surface.DrawRect(0, (i - 1) * 4, w, 2)
    end
end
```
Reason: This avoids constructing a new `Color` every iteration and, when the color stays constant, also avoids repeating the same `surface.SetDrawColor` call inside the loop.


```lua
local sin = math.sin

for i = 1, n do
    out[i] = sin(i)
end
```
Reason: Caching `math.sin` in a local avoids repeated table/global lookup in the hot loop.


```lua
local cachedLocalPlayer
local LocalPlayer = LocalPlayer
local IsValid = IsValid

local function LP()
    local ply = cachedLocalPlayer
    if IsValid(ply) then
        return ply
    end

    ply = LocalPlayer()
    if IsValid(ply) then
        cachedLocalPlayer = ply
    end

    return ply
end

hook.Add("Think", "FastLocalPlayerUse", function()
    local ply = LP()
    if not IsValid(ply) then return end

    local pos = ply:GetPos()
    local vel = ply:GetVelocity()
    local alive = ply:Alive()

    -- use ply for the rest of the hot path
end)
```
Reason: this caches the local player entity in a Lua upvalue and only refreshes it when invalid, so hot code avoids repeated global lookups and repeated `LocalPlayer()` calls.


```lua
local OPPOSITE_DOT = -0.8 -- closer to -1 means stricter

local function ArePlayersRoughlyFacingEachOther(ply1, ply2)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    return aim1:Dot(aim2) <= OPPOSITE_DOT
end
```
Reason: `GetAimVector()` returns normalized vectors, so one dot product tells you how opposite the two aim directions are; thresholding that value is much cheaper than computing an angle with `math.acos`.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is generally a bit faster for a helper you control because a direct call, especially to a local function, avoids the method lookup that `ply:SomeHelper()` usually implies; the difference is small, so prefer `:` only when it is truly a player method.


```lua
MsgN("[debug] hot path hit")
```
Reason: `MsgN` is generally faster than `print` in Garry's Mod because it writes to the console more directly with less formatting overhead, which matters in a hot path.


```lua
local sum = 0
local t = numbers
local n = #t

for i = 1, n do
    sum = sum + t[i]
end
```
Reason: `numeric for` is typically fastest for a large dense array because it does direct indexed access and avoids the iterator overhead of `pairs` and `ipairs`.


```lua
-- Instead of chaining fn.Filter(...) then fn.Map(...), fuse the pipeline.
local IsValid = IsValid
local players = player.GetAll()

local copNames = {}
local n = 0

for i = 1, #players do
    local p = players[i]
    if IsValid(p) and p:Alive() and p:isCP() then
        n = n + 1
        copNames[n] = p:Nick()
    end
end

-- copNames now contains the mapped result for the filtered players.
```
Reason: A single numeric `for` loop does the filter and map in one pass, which avoids fn combinator call overhead, extra closures, and intermediate table allocations.


```lua
local cachedPlayers = {}
local playerIndex = {}

for i, ply in ipairs(player.GetAll()) do
    cachedPlayers[i] = ply
    playerIndex[ply] = i
end

local function addPlayer(ply)
    if playerIndex[ply] then return end

    local i = #cachedPlayers + 1
    cachedPlayers[i] = ply
    playerIndex[ply] = i
end

local function removePlayer(ply)
    local i = playerIndex[ply]
    if not i then return end

    local last = #cachedPlayers
    local lastPly = cachedPlayers[last]

    cachedPlayers[i] = lastPly
    cachedPlayers[last] = nil
    playerIndex[ply] = nil

    if lastPly ~= ply then
        playerIndex[lastPly] = i
    end
end

hook.Add("PlayerInitialSpawn", "PlayerCacheAdd", addPlayer)
hook.Add("PlayerDisconnected", "PlayerCacheRemove", removePlayer)

hook.Add("Tick", "FastPerPlayerTick", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- per-player tick work here
    end
end)
```
Reason: This removes the per-tick `player.GetAll()` call and keeps the hot path to a plain cached-array loop, while join/leave hooks pay the small update cost only when membership changes.


```lua
local tempByEntIndex = {}

local function SetTempValue(ply, value)
    tempByEntIndex[ply:EntIndex()] = value
end

local function GetTempValue(ply)
    return tempByEntIndex[ply:EntIndex()]
end

hook.Add("PlayerDisconnected", "ClearTempValue", function(ply)
    tempByEntIndex[ply:EntIndex()] = nil
end)

-- usage
SetTempValue(ply, value)
local value = GetTempValue(ply)
```
Reason: A plain Lua table keyed by `EntIndex()` avoids repeated userdata field lookup on `ply.someField`, so hot reads are cheaper; clearing on disconnect avoids index reuse bugs.


```lua
local values = {
    "weapon_pistol",
    "weapon_smg1",
    "weapon_shotgun",
    "weapon_crowbar",
}

for i = 1, #values do
    local value = values[i]
    -- use value
end
```
Reason: Sequential number-indexed arrays use the table's array part and avoid hash lookup overhead, so they iterate faster than string-keyed maps in hot loops.


```lua
local R, G, B, A = 255, 128, 64, 255

hook.Add("HUDPaint", "FastDraw", function()
    surface.SetDrawColor(R, G, B, A)
    surface.DrawRect(100, 100, 200, 40)
end)
```
Reason: Passing raw numeric channels avoids the extra Color/table path and per-call component extraction, so it is faster in a hot draw loop.


```lua
local steamID64 = ply:SteamID64()
local coins = tonumber(sql.QueryValue("SELECT coins FROM player_data WHERE steamid64 = " .. sql.SQLStr(steamID64)) or 0)
```
Reason: Local SQLite via Garry's Mod `sql` library is typically lower latency on a single server because it avoids network round-trips and remote MySQL connection overhead.


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

local function GetSteamIDCached(ply)
    local sid = steamIdCache[ply]
    if sid ~= nil then
        return sid
    end

    sid = ply:SteamID()
    steamIdCache[ply] = sid
    return sid
end

-- Hot path
for i = 1, #players do
    local ply = players[i]
    local sid = GetSteamIDCached(ply)

    -- use sid as many times as needed here
end
```
Reason: It replaces repeated `ply:SteamID()` engine calls with one lookup per player, and the weak-key cache cleans itself up when player objects go away.


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

-- Fast: collect pieces, join once
local parts = {}
for i = 1, #pieces do
    parts[i] = pieces[i]
end

local s_fast = table.concat(parts)
```
Reason: `table.concat` does one final join, avoiding the repeated reallocations and full-string copies caused by `s = s .. piece` inside a loop.


```lua
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is the direct plain-rectangle path, while `draw.RoundedBox(0, ...)` still pays extra Lua helper overhead for a rounded-box API you are not using.


```lua
surface.CreateFont("PerfHUDText", {
    font = "Tahoma",
    size = 24,
    weight = 500,
    antialias = true,
})

local FONT = "PerfHUDText"
local X, Y = 32, 32
local TEXT = "Single-line HUD text"

hook.Add("HUDPaint", "PerfSurfaceText", function()
    surface.SetFont(FONT)
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(X, Y)
    surface.DrawText(TEXT)
end)
```
Reason: Direct `surface` text calls avoid the extra wrapper work in `draw.DrawText` and the multi-pass outline draws in `draw.SimpleTextOutlined`, so single-line text is cheaper per frame.


```lua
local len = #myTable
```
Reason: `#` is the preferred way to get the length of a sequential array-like table; it is the native Lua length operator and avoids the overhead and different semantics of functions like `table.Count`.


```lua
local t = bigSequentialTable

-- Faster when you do not need to preserve existing references to the same table.
t = {}
```
Reason: `t = {}` is generally faster because rebinding is O(1), while `table.Empty(t)` iterates and clears every entry; use `table.Empty(t)` only when other code must keep the same table reference.


```lua
local allowed = {
    ["weapon_crowbar"] = true,
    ["weapon_pistol"] = true,
    ["weapon_shotgun"] = true,
}

if allowed[wepClass] then
    -- value exists
end
```
Reason: A set-style table uses a direct hash lookup, so the check is typically O(1) instead of the O(n) linear scan done by `table.HasValue` on a list.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3,
}
```
Reason: Putting known fields in the table constructor is faster because the table is created and populated in one step, with fewer separate field writes and better sizing up front.


```lua
local values = { "a", "b", "c", "d" }
local randomValue = values[math.random(#values)]
```
Reason: For sequential tables, direct index selection with `math.random(#values)` avoids `table.Random`'s extra work and is faster.


```lua
local x2 = x * x
```
Reason: `x * x` is the preferred fast form in tight loops because it avoids the slower generic exponentiation path used by `x ^ 2`.


```lua
for _, ply in player.Iterator() do
    -- use ply here
end
```
Reason: `player.Iterator()` iterates connected players directly without building the temporary table that `player.GetAll()` returns.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- visit each prop_physics entity here
end
```
Reason: `ents.FindByClass` returns only entities of the requested class, so this avoids building a table of every entity in the map first.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a function for the `Think` hook, and `MyAddon.Think` is the callback identifier.


```lua
if IsValid(ent) then
```
Reason: `IsValid` is the standard Garry's Mod check for an entity reference that is still alive and usable before calling methods on it.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle incoming message here
end)
```
Reason: `net.Receive` registers the client or server callback for the named Garry's Mod net message, and `MyAddon.Sync` is the message identifier.


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

-- reuse it instead of calling Angle() every time in a hot path
return ZERO_ANGLE
```
Reason: `Angle(0, 0, 0)` allocates a new Angle object; reusing one shared zero angle avoids repeated construction in hot paths.


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

local c = addon_color
```
Reason: A flat local avoids repeated table lookups and is the fastest frequent-read option; nested tables are better for organization, but not for hot-path reads.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores the live job name in its own networked variable API, so `getDarkRPVar("job")` is the preferred, DarkRP-aware way to read it instead of raw `GetNWString("job")`.


```lua
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root, so it is the preferred way to do a vector threshold check.


```lua
for ent in ents.Iterator() do
    -- visit every entity here
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient way to iterate all entities without building a full table first.


```lua
local pos = ply:GetPos()
local radius = 512
local ents = ents.FindInSphere(pos, radius)
```
Reason: `ents.FindInSphere` is a fast built-in broad-phase spatial query for “near a player” checks and is the usual cheap pick when you want a radius search without defaulting to `FindInPVS`.


```lua
local pos = somePosition
local radius = 512
local radiusSqr = radius * radius
local nearbyPlayers = {}

for _, ply in ipairs(player.GetAll()) do
    if ply:GetPos():DistToSqr(pos) <= radiusSqr then
        nearbyPlayers[#nearbyPlayers + 1] = ply
    end
end
```
Reason: `player.GetAll()` avoids building and scanning non-player entities from `ents.FindInSphere`, and `DistToSqr` skips the expensive square root while still giving the same radius test.


```lua
for i = 1, n do
    -- work
end
```
Reason: In Garry's Mod Lua, the numeric `for` loop is generally faster than a `while` loop for simple counting because it is a built-in loop form with less per-iteration overhead.


```lua
-- Faster: one hook.Run per tick, passing the whole player list once.
local players = player.GetAll()
hook.Run("MyCustomLogic", players)

-- Slower: hook.Run once per player.
for i = 1, #players do
    hook.Run("MyCustomLogic", players[i])
end
```
Reason: One hook.Run call avoids per-player hook dispatch overhead, so it is cheaper each tick.


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

-- use hp for all three draws in this frame
```
Reason: cache `LocalPlayer()` and `Health()` once per frame so the hook avoids repeating the same lookup and method call three times.


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

for i = 1, #items do
    surface.SetDrawColor(WHITE)
    surface.DrawRect(items[i].x, items[i].y, items[i].w, items[i].h)
end
```
Reason: `Color(255,255,255)` allocates a new color table every iteration; hoisting one shared white color avoids per-loop allocation and cuts GC work.


```lua
local sin = math.sin

for i = 1, 100000 do
    local v = sin(i)
    -- use v
end
```
Reason: Caches `math.sin` in a local upvalue so the hot loop avoids repeated table lookups.


```lua
local lp = nil

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

-- Use `lp` instead of calling `LocalPlayer()` repeatedly in hot code.
if IsValid(lp) then
    print(lp:Nick())
end
```
Reason: Caching the entity in a local avoids repeated global/function lookup and keeps hot paths on a direct local read.


```lua
-- Fast mutual look check using dot products (no acos).
-- Threshold is cosine of the max allowed deviation from directly facing.
-- Example: 0.75 ~= within about 41.4 degrees of each other.
local function LookingAtEachOther(p1, p2, threshold)
    threshold = threshold or 0.75

    local e1 = p1:EyeAngles()
    local e2 = p2:EyeAngles()

    local d1 = e1:Forward()
    local d2 = e2:Forward()

    local to2 = (p2:EyePos() - p1:EyePos()):GetNormalized()
    local to1 = -to2

    return d1:Dot(to2) >= threshold and d2:Dot(to1) >= threshold
end
```
Reason: Dot products are cheaper than converting to angles and calling `math.acos`, and they directly test whether each player’s aim direction points toward the other.


```lua
SomeHelper(ply)
```
Reason: For a helper you control, the free function avoids method-call sugar and is the generally cheaper, clearer call style in Lua; the difference is small, but `SomeHelper(ply)` is the better default.


```lua
MsgN("debug: reached hot path")
```
Reason: `MsgN` writes directly to the console with less formatting work than `print`, so it is the cheaper choice for a hot-path debug line.


```lua
for i = 1, #t do
    local v = t[i]
    -- use v
end
```
Reason: For a large sequential array-like table, a numeric `for` is typically fastest because it avoids the iterator overhead of `pairs` and `ipairs` and uses direct indexed access.


```lua
-- Faster than chaining DarkRP fn combinators: one pass, one output table.
-- Example pipeline: keep numbers > 0, double them, stop after max_n items.
local function filter_map_fast(list, pred, map, max_n)
  local out = {}
  local n = 0

  for i = 1, #list do
    local v = list[i]
    if pred(v, i) then
      n = n + 1
      out[n] = map(v, i)
      if max_n and n >= max_n then
        break
      end
    end
  end

  return out, n
end

-- Usage.
local input = { -2, -1, 0, 1, 2, 3, 4 }
local result = filter_map_fast(input,
  function(v) return v > 0 end,
  function(v) return v * 2 end
)

-- result = { 2, 4, 6, 8 }
```
Reason: It does the same filter/map work in a single numeric for-loop with no intermediate tables or combinator closures, so it cuts allocation and call overhead.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "RefreshPlayerCacheOnJoin", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "RefreshPlayerCacheOnLeave", RefreshPlayerCache)

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

-- optional: seed the cache on startup / script reload
RefreshPlayerCache()
```
Reason: It avoids rebuilding `player.GetAll()` and the iterator work every tick by keeping a shared cache that is updated only on player join/leave events.


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

-- write
PlayerData[ply] = PlayerData[ply] or {}
PlayerData[ply].someField = value

-- read
local data = PlayerData[ply]
local field = data and data.someField
```
Reason: A weak-key side table keeps temporary per-player state out of the player object and gives faster repeated reads through one indexed table lookup, instead of repeated custom field access on `ply`.


```lua
-- Faster for iteration: sequential number-indexed array
local array = { "a", "b", "c" }

for i = 1, #array do
    local v = array[i]
    -- iterate values
end

-- Slower for iteration: string-keyed map
local map = {
    first = "a",
    second = "b",
    third = "c",
}

for k, v in pairs(map) do
    -- iterate key/value pairs
end
```
Reason: Sequential arrays are the faster table shape for fixed iteration because numeric indexing is simpler and more cache-friendly than string-keyed map lookup and generic pair traversal.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numeric channels avoids allocating or unpacking a `Color` object in a hot draw loop, so it is the faster call style.


```lua
sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
```
Reason: For a single Garry's Mod server with no sync needs, local SQLite is typically lower latency because it avoids network round trips and remote server overhead; MySQL only wins if you need external access, concurrency, or durability patterns beyond one server.


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

local function GetSteamID(ply)
    local sid = steamid_cache[ply]
    if sid ~= nil then
        return sid
    end

    sid = ply:SteamID()
    steamid_cache[ply] = sid
    return sid
end

hook.Add("EntityRemoved", "SteamIDCache_Clear", function(ent)
    if steamid_cache[ent] ~= nil then
        steamid_cache[ent] = nil
    end
end)

-- hot path
-- local sid = GetSteamID(ply)
```
Reason: Caches the SteamID per player entity so repeated hot-path calls avoid redoing the same method lookup, while the weak-key table lets entries fall out when the player entity is gone.


```lua
-- Slow: repeated concatenation creates lots of intermediate strings.
local out = ""
for i = 1, 10000 do
    out = out .. "piece" .. i .. "\n"
end

-- Faster: collect pieces, then join once.
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece"
    parts[#parts + 1] = tostring(i)
    parts[#parts + 1] = "\n"
end
local fast = table.concat(parts)

print(#out, #fast)
```
Reason: `table.concat` builds the final string in one pass, avoiding the repeated temporary strings and reallocations caused by `..` in a loop.


```lua
draw.NoTexture()
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` draws a plain filled rectangle directly, so it avoids the extra rounded-box path and is a slightly faster fit for non-rounded rects.


```lua
local font_name = "DermaDefault"
local text = "Hello world"
local x, y = 100, 100

surface.SetFont(font_name)
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.DrawText` is the lightest path for a single-line string; it avoids the extra alignment, size, and outline work done by `draw.DrawText` and especially `SimpleTextOutlined`.


```lua
local n = #tbl
```
Reason: In Garry's Mod Lua, the preferred way to get the length of a sequential array-like table is the length operator `#`.


```lua
-- Generally faster when you only need to drop the old table and do not need
-- other references to see it emptied:
t = {}

-- Use this when you must keep the same table object alive for other references:
-- table.Empty(t)
```
Reason: `t = {}` is usually faster for simply discarding a large table because it replaces the reference instead of clearing every entry in place; `table.Empty(t)` is only needed when other code still holds the same table object.


```lua
-- Fast membership check: use a set-style table with boolean true values.
local allowed = {
    ["apple"] = true,
    ["banana"] = true,
    ["orange"] = true,
}

local value = "banana"

if allowed[value] then
    print("exists")
end

-- Slow on large lists:
-- if table.HasValue(list, value) then ... end
```
Reason: direct table lookup is O(1) average time, while `table.HasValue` scans the list linearly.


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

-- Slower: create empty table, then assign fields
-- local t = {}
-- t.x = 1
-- t.y = 2
-- t.z = 3
```
Reason: The constructor is faster because Lua can allocate and initialize the table in one step, while post-assignment does separate table writes for each field.


```lua
local t = seq_table
local v = t[math.random(#t)]
```
Reason: `table.Random` does extra work for generic tables; for a dense sequential array, picking a random index directly avoids that overhead.


```lua
local xx = x * x
```
Reason: `x * x` is the fastest clear form here; it avoids a function call and works well in tight loops.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- your code here
end
```
Reason: `player.GetAll()` returns the current connected players as an array, so `ipairs` is the direct loop for visiting each one in order.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- visit ent here
    end
end
```
Reason: `ents.Iterator()` walks entities directly, so it filters `prop_physics` without allocating a table of all map entities first.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a callback for the `Think` hook, and the string identifier `MyAddon.Think` names the callback so it can be referenced or removed later.


```lua
if IsValid(ent) then
    -- safe to call entity methods here
end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check that returns false for `nil`, `NULL`, removed, or otherwise invalid entity references.


```lua
net.Receive("MyAddon.Sync", function()
    -- handle incoming payload here
end)
```
Reason: `net.Receive` registers the callback that runs when the `MyAddon.Sync` message arrives.


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

-- Hot path: reuse the cached zero angle instead of allocating a new one.
local ang = ZERO_ANGLE
```
Reason: Reusing one preallocated zero Angle avoids repeated allocations and is faster than calling `Angle()` every time; only copy it if you need to mutate the result.


```lua
local myaddon_color = Color(255, 128, 0)

-- frequent read
local c = myaddon_color
```
Reason: A flat local/upvalue avoids repeated table lookups (`myaddon.config.color`), so it is faster on a hot read path.


```lua
local jobName = ply:getDarkRPVar("job") -- preferred DarkRP API
-- instead of: ply:GetNWString("job")
```
Reason: `getDarkRPVar("job")` uses DarkRP's own accessor for job state, while `GetNWString("job")` reaches into the networked storage directly.


```lua
if pos1:DistToSqr(pos2) <= threshold * threshold then
    -- within range
end
```
Reason: `DistToSqr` compares squared distance, so it avoids the extra square root when you only need a threshold check.


```lua
for ent in ents.Iterator() do
    -- visit ent here
end
```
Reason: `ents.Iterator()` is the efficient wiki-recommended way to walk all entities without allocating the full `ents.GetAll()` table.


```lua
local function GetNearbyEntities(ply, radius)
    local pos = ply:GetPos()
    local mins = pos - Vector(radius, radius, radius)
    local maxs = pos + Vector(radius, radius, radius)

    local nearby = ents.FindInBox(mins, maxs)
    local radiusSqr = radius * radius
    local out = {}

    for i = 1, #nearby do
        local ent = nearby[i]
        if IsValid(ent) and ent ~= ply and ent:GetPos():DistToSqr(pos) <= radiusSqr then
            out[#out + 1] = ent
        end
    end

    return out
end
```
Reason: `ents.FindInBox` is usually the cheaper built-in broad-phase query than `FindInSphere`, and it lets you keep the result tight with a squared-distance filter.


```lua
local function PlayersInSphere(pos, radius)
    local radiusSqr = radius * radius
    local result = {}

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

    return result
end
```
Reason: It scans only players instead of all entities, and `DistToSqr` avoids expensive square-root math.


```lua
for i = 1, n do
    -- tight counting loop
end
```
Reason: In Garry's Mod Lua, the numeric `for` loop is generally faster than a `while` loop for simple counting because the VM handles the counter setup and increment more efficiently.


```lua
hook.Add("Think", "NotifyAllPlayersOnce", function()
    local players = player.GetAll()
    hook.Run("MyCustomTick", players)
end)
```
Reason: one `hook.Run` does the dispatch work once, so it avoids the per-player call overhead of looping and invoking the hook system repeatedly.


```lua
hook.Add("HUDPaint", "DrawHealth", function()
    local lp = LocalPlayer()
    local health = lp:Health()

    draw.SimpleText(health, "DermaDefault", 50, 50, color_white)
    draw.SimpleText(health, "DermaDefault", 50, 70, color_white)
    draw.SimpleText(health, "DermaDefault", 50, 90, color_white)
end)
```
Reason: `LocalPlayer():Health()` is computed once and reused, which removes two repeated lookups/calls in the same frame.


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

for i = 1, #items do
    surface.SetDrawColor(WHITE)
    -- paint item...
end
```
Reason: `Color(255, 255, 255)` allocates a new color each iteration; caching the white color once removes that per-loop work.


```lua
local sin = math.sin

for i = 1, n do
    local v = sin(i * dt)
    -- use v
end
```
Reason: A local upvalue is faster to access than repeated table lookups like `math.sin` inside a hot loop.


```lua
local _LocalPlayer = LocalPlayer
local cachedLP

local function LP()
    if not IsValid(cachedLP) then
        cachedLP = _LocalPlayer()
    end
    return cachedLP
end

-- hot path usage:
-- local ply = LP()
```
Reason: `LocalPlayer` is resolved once into a local upvalue, and the player entity is cached so hot code avoids repeated global/function lookup work.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, dotThreshold)
    dotThreshold = dotThreshold or 0.95 -- lower = looser cone

    local eye1 = ply1:EyePos()
    local eye2 = ply2:EyePos()

    local to2 = (eye2 - eye1):GetNormalized()
    local to1 = -to2

    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()

    return aim1:Dot(to2) >= dotThreshold
       and aim2:Dot(to1) >= dotThreshold
end
```
Reason: Dot products give a cheap cone test for alignment, so this checks mutual facing with only normalization and multiplies, no trigonometry.


```lua
SomeHelper(ply)
```
Reason: for a helper you control, the explicit-argument form is generally the better fit and is at least as fast, usually a bit faster, because `ply:SomeHelper()` is just method-call sugar with an extra table lookup/dispatch step.


```lua
Msg("[debug] ", value, "\n")
```
Reason: `Msg` writes directly to the console without `print`'s extra formatting work, so it is cheaper in a hot path.


```lua
local t = numbers
local n = #t
for i = 1, n do
    local v = t[i]
    -- use v
end
```
Reason: numeric `for` with a cached length is typically fastest for a large sequential array-like table; `ipairs` adds iterator overhead, and `pairs` is slower and does not guarantee array order.


```lua
-- Fused filter+map: one pass, one result table, no combinator chain overhead.
local function filter_map(src, pred, map)
    local out = {}
    local n = 0

    for i = 1, #src do
        local v = src[i]
        if pred(v, i) then
            n = n + 1
            out[n] = map(v, i)
        end
    end

    return out
end

-- Example: keep valid players and map to their names.
local players = player.GetAll()
local names = filter_map(players,
    function(p) return IsValid(p) and p:Alive() end,
    function(p) return p:Nick() end
)

-- If you need more steps, fuse them into the same loop instead of chaining fn combinators.
local function filter_map_map(src, pred, map1, map2)
    local out = {}
    local n = 0

    for i = 1, #src do
        local v = src[i]
        if pred(v, i) then
            n = n + 1
            out[n] = map2(map1(v, i), i)
        end
    end

    return out
end
```
Reason: A fused numeric for-loop avoids DarkRP fn combinator overhead, extra closures, and intermediate tables while doing the same filter/map work in one pass.


```lua
if SERVER then
    local cachedPlayers = {}

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

    hook.Add("Initialize", "RefreshPlayerCache_Init", RefreshPlayerCache)
    hook.Add("PlayerInitialSpawn", "RefreshPlayerCache_Join", function()
        RefreshPlayerCache()
    end)
    hook.Add("PlayerDisconnected", "RefreshPlayerCache_Leave", function()
        RefreshPlayerCache()
    end)

    hook.Add("Think", "MyFastThink", function()
        for _, ply in ipairs(cachedPlayers) do
            -- work with ply
        end
    end)
end
```
Reason: The Think hook reuses a cached player list, so it avoids rebuilding `player.GetAll()` every tick and only refreshes when the roster changes.


```lua
local temp = setmetatable({}, { __mode = "k" }) -- weak keys for temporary player data

-- write
function SetTempData(ply, value)
    temp[ply] = value
end

-- read
function GetTempData(ply)
    return temp[ply]
end
```
Reason: a local side-table keyed by the player avoids repeated entity field/metatable lookups on `ply.someField`, which is faster for hot reads.


```lua
-- Faster for iteration: sequential number-indexed array
local values = {
    "alpha",
    "beta",
    "gamma",
}

for i = 1, #values do
    local v = values[i]
    -- use v
end

-- Slower for iteration: string-keyed map
local map = {
    first = "alpha",
    second = "beta",
    third = "gamma",
}

for k, v in pairs(map) do
    -- use k, v
end
```
Reason: Sequential number-indexed arrays are the faster table shape for iteration because Lua can traverse them with simpler contiguous access, while string-keyed maps need hash lookups and general `pairs` traversal.


```lua
-- Faster in hot draw paths: pass raw numbers instead of a Color object.
surface.SetDrawColor(255, 128, 64, 255)
```
Reason: Raw `r,g,b,a` numbers avoid the extra Color table/object handling, so they are the faster call style in tight draw loops.


```lua
local rows = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345'")
```
Reason: For a single Garry's Mod server with no cross-server sync, local SQLite usually has lower read/write latency than remote MySQL because it avoids network round trips and remote connection overhead.


```lua
local steamid_cache = setmetatable({}, { __mode = "k" }) -- weak keys, auto-drops dead players

local function SteamIDCached(ply)
    local steamid = steamid_cache[ply]
    if steamid ~= nil then
        return steamid
    end

    steamid = ply:SteamID()
    steamid_cache[ply] = steamid
    return steamid
end

-- hot path
for _, ply in ipairs(player.GetAll()) do
    local steamid = SteamIDCached(ply)
    -- use steamid repeatedly here
end
```
Reason: It turns repeated `ply:SteamID()` calls into one lookup per player and one weak-key table hit afterward, which is faster in hot paths and avoids leaking cache entries after players leave.


```lua
-- Slow: repeated .. creates a new string every time.
-- local s = ""
-- for i = 1, 10000 do
--   s = s .. "piece" .. i
-- end

-- Fast: collect pieces, join once.
local parts = {}
local n = 0

for i = 1, 10000 do
  n = n + 1
  parts[n] = "piece" .. i
end

local big = table.concat(parts)
```
Reason: `table.concat` builds the final string once, so it avoids the repeated reallocations and copies caused by chaining `..` in a large loop.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` adds rounded-box overhead you do not need for plain rectangles; `surface.DrawRect` is the direct fill path and is slightly cheaper per draw.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: `surface.SetFont` + `surface.SetTextPos` + `surface.SetTextColor` + `surface.DrawText` is the lightest path for a single-line string; it avoids the extra wrapper work in `draw.DrawText`, and `SimpleTextOutlined` is slower because it draws the text multiple times for the outline.


```lua
local n = #tbl
```
Reason: `#` is the standard length operator for sequential array-like tables in Lua, and is the preferred way to get their element count when the table is a proper sequence.


```lua
-- Generally faster when you can drop the old table reference.
t = {}
```
Reason: `t = {}` only rebinds the variable, while `table.Empty(t)` walks and clears every slot in the existing table, so rebinding is usually cheaper for large tables.


```lua
local allowed = {
  weapon_pistol = true,
  weapon_smg1 = true,
  weapon_ar2 = true,
}

if allowed[value] then
  -- value exists in the set
end
```
Reason: Key lookup in a set table is O(1) average, while `table.HasValue` scans a list linearly.


```lua
local t = {
    foo = 1,
    bar = 2,
}
```
Reason: The constructor is usually faster because Lua can allocate and initialize the table in one step instead of creating `{}` and then doing separate field assignments.


```lua
local function RandomSequential(t)
    return t[math.random(#t)]
end
```
Reason: `table.Random` handles general tables; for a sequential array, direct `#t` plus one indexed lookup is faster because it skips extra table traversal and key handling.


```lua
local xx = x * x
```
Reason: `x * x` is the direct, allocation-free way to square a number and is faster than calling `math.pow` in a tight loop.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- your code here
end
```
Reason: `player.GetAll()` returns the current player list, and `ipairs` is the idiomatic way to iterate that array-style table in Lua.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: `ents.Iterator()` walks entities one at a time, so you can filter `prop_physics` without building a full entity table.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` registers a callback on Garry's Mod's `Think` hook under the identifier `MyAddon.Think`.


```lua
if not IsValid(ent) then return end
```
Reason: `IsValid(ent)` is the standard Garry's Mod check for a valid, still-usable entity reference before calling entity methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the incoming message here
end)
```
Reason: `net.Receive` is the Garry's Mod API used to register a callback for an incoming net message by name.


```lua
local zeroAngle = angle_zero

-- Hot path: use the shared zero Angle instead of allocating a new one.
local ang = zeroAngle
```
Reason: `angle_zero` is a shared zero-angle constant, so it avoids per-call `Angle()` allocation; if you need to mutate it, keep a reusable scratch `Angle` and call `:Zero()` on that.


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

if addon_color then
    -- use addon_color
end
```
Reason: a cached local/upvalue is faster to read than repeated nested table or global lookups in Lua.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores the job name as a DarkRPVar, so `ply:getDarkRPVar("job")` is the supported API instead of reading the NWString directly.


```lua
if v1:DistToSqr(v2) < (threshold * threshold) then
    -- within range
end
```
Reason: `DistToSqr` avoids the square root, so it is the cheaper way to do a distance threshold check.


```lua
for ent in ents.Iterator() do
    -- visit each entity here
end
```
Reason: `ents.Iterator()` is the efficient entity traversal path, so it avoids building the full `ents.GetAll()` table when a snapshot copy is not needed.


```lua
local function GetNearbyEntities(ply, radius)
    local center = ply:GetPos()
    return ents.FindInSphere(center, radius)
end

-- example
local entsNear = GetNearbyEntities(ply, 500)
```
Reason: `ents.FindInSphere` is one of the faster built-in proximity queries for a player-centered radius check, and it avoids the heavier PVS-style visibility query.


```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()` only iterates players, and `DistToSqr` avoids the expensive square root and the extra entity scan/filter pass from `ents.FindInSphere`.


```lua
for i = 1, n do
    -- work
end
```
Reason: In Lua, a numeric `for` loop is generally faster than an equivalent `while` loop because the VM handles the loop counter and termination more efficiently.


```lua
-- Faster: dispatch once per tick and pass all players in one call.
hook.Run("MyCustomLogicTick", player.GetAll())

-- Slower: dispatch once per player.
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("MyCustomLogicTick", ply)
-- end
```
Reason: One `hook.Run` does one dispatch and one argument setup; the loop version repeats that overhead for every player.


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

    local hp = lp:Health()

    draw.SimpleText(hp, "Trebuchet24", 20, 20, color_white)
    draw.SimpleText(hp, "Trebuchet24", 20, 40, color_white)
    draw.SimpleText(hp, "Trebuchet24", 20, 60, color_white)
end)
```
Reason: `LocalPlayer():Health()` is resolved once per frame instead of three times, so the hook does less repeated lookup work.


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

hook.Add("HUDPaint", "MyPaintLoop", function()
    for i = 1, 100 do
        surface.SetDrawColor(WHITE)
        surface.DrawRect(i, 10, 1, 1)
    end
end)
```
Reason: Reuses one cached Color instead of allocating a new Color(255,255,255) table every loop iteration.


```lua
local sin = math.sin

for i = 1, #angles do
    sum = sum + sin(angles[i])
end
```
Reason: Localizing `math.sin` avoids repeating the table lookup inside the hot loop.