Uses IsValid for entity/object validity.


Answer must contain 0 through 0 candidate loops.


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


```lua
local angle_zero = angle_zero
```
Reason: Localizing the globally pre-allocated `angle_zero` constant avoids both the garbage collection overhead of allocating new Angle objects and the global table lookup overhead in hot paths.


```lua
local config_color = Color(255, 0, 0)
local val = config_color
```
Reason: Local variables are stored in virtual machine registers and accessed directly by index, completely bypassing the multiple expensive hash table lookups required to resolve nested tables.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system via `getDarkRPVar` which is more efficient than standard NWVars and correctly retrieves custom job names set by players using the `/job` command.


```lua
local threshold = 100
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- Vectors are within the threshold distance
end
```
Reason: Using Vector:DistToSqr avoids the computationally expensive square root operation performed by Vector:Distance.


```lua
for _, ent in ipairs(ents.Iterator()) do
    -- Code to execute on each entity
end
```
Reason: ents.Iterator() is preferred over ents.GetAll() because it returns a read-only reference to the internal entity table, avoiding the CPU and memory overhead of creating a new table on every call.


```lua
local ply = Entity(1) -- Example player reference
local nearbyEnts = ents.FindInSphere(ply:GetPos(), 512)
```
Reason: ents.FindInSphere is implemented in C++ and utilizes the Source Engine's spatial partitioning tree to quickly query entities within a radial distance, making it significantly faster than checking distances manually or using more complex FindIn* shapes.


```lua
local function GetPlayersInSphere(pos, radius)
	local players = {}
	local count = 0
	local radiusSqr = radius * radius

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

	return players
end
```
Reason: Iterating over players with `player.Iterator()` avoids allocating tables, and checking distance using `DistToSqr` avoids expensive square root calculations while bypassing `ents.FindInSphere`'s costly spatial partitioning search over thousands of server entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are optimized at the Lua VM level, using dedicated bytecode instructions and register allocations for the counter, increment, and comparison instead of manual arithmetic and conditional evaluations.


```lua
-- FASTER: Calling hook.Run once with all players
hook.Add("Tick", "NotifyPlayersFast", function()
    hook.Run("OnPlayersTick", player.GetAll())
end)

-- SLOWER: Looping players and calling hook.Run per player
hook.Add("Tick", "NotifyPlayersSlow", function()
    local players = player.GetAll()
    for i = 1, #players do
        hook.Run("OnPlayerTick", players[i])
    end
end)
```
Reason: Calling hook.Run once per tick incurs the overhead of hook lookup and execution only once, whereas calling it per-player multiplies that lookup and call overhead by the player count.


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

	local hp = ply:Health()
	draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 50, color_white)
	draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 70, color_white)
	draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 90, color_white)
end)
```
Reason: Caching the LocalPlayer entity to a local variable and storing the result of `:Health()` once per frame avoids repeating expensive Lua-to-C boundary crossings and table lookups.


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

hook.Add("HUDPaint", "PaintHook", function()
    -- Use colorWhite instead of calling Color(255, 255, 255)
end)
```
Reason: Calling the Color function creates a new table on every frame, generating garbage and causing garbage collection overhead, whereas caching the color table outside the loop references a single persistent instance.


```lua
local sin = math.sin

-- Inside the hot loop:
for i = 1, 1000000 do
    local val = sin(i)
end
```
Reason: Localizing the global function caches its reference, replacing slow table lookups (looking up `math` in the globals table, then `sin` in the `math` table) with fast local register access.


```lua
local lp
local function GetLocalPlayerSafe()
	if not lp or not lp:IsValid() then
		lp = LocalPlayer()
	end
	return lp
end
```
Reason: Caching the player object in a local variable avoids repeated expensive global table lookups and engine calls to LocalPlayer() while ensuring the entity has loaded and is valid.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- Approximately 45 degrees tolerance (cos(45) ≈ 0.707)
    local dir = ply2:GetShootPos() - ply1:GetShootPos()
    dir:Normalize() -- Normalizes the vector in-place, which is faster and avoids new allocations
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: The dot product of the unit aim vectors against the normalized direction vector between players determines alignment using basic arithmetic (multiplications and additions), avoiding expensive trigonometric function calls like math.acos.


```lua
SomeHelper(ply)
```
Reason: The colon syntax `ply:SomeHelper()` is syntactic sugar for `ply.SomeHelper(ply)`, which requires a table/metatable lookup on the player object and is slower than a direct function call.


```lua
MsgN("Debug message")
```
Reason: MsgN is a direct C-implemented engine function that bypasses the Lua-side overhead of print, which converts all arguments to strings and concatenates them with tabs before printing.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Numeric for loops avoid the iterator function overhead of ipairs and pairs, mapping directly to highly optimized bytecode instructions in Garry's Mod's LuaJIT environment.


```lua
local results = {}
local count = 0
for i = 1, #inputList do
    local val = inputList[i]
    if val > 10 then -- Filter
        count = count + 1
        results[count] = val * 2 -- Map
    end
end
```
Reason: A direct procedural loop executes in a single pass, avoiding the high CPU overhead of nested closures, function calls, and intermediate table allocations generated by the DarkRP fn library.


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

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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCacheOnSpawn", function()
    timer.Simple(0, updatePlayerCache)
end)

hook.Add("PlayerDisconnected", "UpdatePlayerCacheOnDisconnect", function()
    timer.Simple(0, updatePlayerCache)
end)

hook.Add("Think", "OptimizedThinkHook", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Perform your tick operations here
        end
    end
end)
```
Reason: Calling player.GetAll() every tick creates a new table each time, causing high garbage collection overhead and CPU strain, whereas caching the table and updating it only on PlayerInitialSpawn and PlayerDisconnected hooks eliminates unnecessary allocations.


```lua
local playerData = {}

-- Writing data
playerData[ply] = value

-- Reading data (fast hot-path)
local value = playerData[ply]

-- Clean up on disconnect to prevent memory leaks
hook.Add("PlayerDisconnected", "CleanPlayerDataCache", function(ply)
    playerData[ply] = nil
end)
```
Reason: Reading `ply.someField` invokes a metatable lookup on the player userdata to search the entity's table, whereas indexing a local Lua table directly with the player object bypasses the metatable lookup and C-boundary entirely.


```lua
local tbl = { "value1", "value2", "value3" }
```
Reason: Sequential number-indexed arrays store values in the table's continuous array portion, allowing LuaJIT to optimize iteration using a numeric for loop with direct array offsets instead of costly hash table lookups.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate r, g, b, a numbers directly is faster because it avoids the overhead of creating, wrapping, or indexing a Color table object, preventing unnecessary garbage collection inside hot rendering hooks.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345';")
```
Reason: Local SQLite runs in-process directly on the server's local disk, eliminating the network transmission and TCP overhead associated with querying a remote MySQL server.


```lua
local Player = FindMetaTable("Player")
local origSteamID = Player.SteamID

function Player:SteamID()
    local steamID = self._cachedSteamID
    if not steamID then
        steamID = origSteamID(self)
        self._cachedSteamID = steamID
    end
    return steamID
end
```
Reason: Overriding the Player metatable method to memoize the SteamID string directly on the player object avoids the overhead of repeatedly calling the engine-level C-function.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece"
end
local result = table.concat(pieces)
```
Reason: Using `table.concat` accumulates the strings in a table and combines them in a single operation, avoiding the performance overhead of creating and garbage-collecting thousands of intermediate strings.


```lua
surface.SetDrawColor(color.r, color.g, color.b, color.a)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect is a low-level engine-facing function that bypasses the overhead of the draw.RoundedBox Lua wrapper, which performs parameter checks and handles rounded corner geometry calculations.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(text)
```
Reason: Low-level `surface` functions are direct C++ bindings, whereas `draw.*` helpers are Lua wrapper functions that introduce overhead by parsing arguments, handling alignment calculations, and splitting strings.


```lua
local tbl = { "one", "two", "three" }
local length = #tbl
```
Reason: The `#` operator is the built-in, most efficient, and preferred way to get the length of a sequential, one-indexed array-like table in Garry's Mod Lua.


```lua
t = {}
```
Reason: Creating a new table with `t = {}` is an O(1) operation, whereas `table.Empty(t)` runs an O(N) loop in Lua to set every key to `nil`, which is significantly slower for large tables.


```lua
-- Set representation (O(1) lookup)
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["cherry"] = true
}

-- Checking existence
if mySet["banana"] then
    -- Value exists in the set
end
```
Reason: Using values as keys in a table allows O(1) direct hash-map lookups instead of table.HasValue's O(N) linear search.


```lua
local tbl = {
    x = 1,
    y = 2,
    z = 3
}
```
Reason: Putting fields in the table constructor allows LuaJIT to pre-allocate the table with the correct hash and array sizes, avoiding the performance overhead of rehashing and resizing that occurs when assigning fields one by one to an empty table.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random internally calls table.GetKeys to support non-sequential tables, which runs in O(N) time and allocates a new table, whereas indexing directly with the length operator runs in O(1) time and allocates no memory.


```lua
local square = x * x
```
Reason: Local multiplication `x * x` is direct and compiled by LuaJIT to a single CPU instruction, avoiding the overhead of the exponentiation operator `^` or calling `math.pow`.


```lua
for _, ply in player.Iterator() do
    -- code
end
```
Reason: player.Iterator() is the modern, optimized alternative to player.GetAll() that avoids table allocation and garbage collection overhead.


```lua
for _, ent in ents.Iterator() do
	if ent:GetClass() == "prop_physics" then
		-- Action to perform on each prop_physics entity
	end
end
```
Reason: Using ents.Iterator() leverages Garry's Mod's internally cached entity list, allowing you to iterate over all entities and filter by class without allocating a new table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback code runs here
end)
```
Reason: Garry's Mod uses the hook.Add function to register callbacks to events like "Think" using a unique identifier.


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: The global `IsValid()` function safely checks if the reference is not nil, is a valid Entity object, and has not been removed from the game, preventing runtime errors that would occur if you called methods directly on a nil or NULL entity reference.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the net message here
end)
```
Reason: net.Receive is the standard Garry's Mod API function used to register a receiver callback for net messages with a specific identifier.


```lua
local zero = Angle()

-- Reuse 'zero' in the hot path. If you need to modify it, reset it in-place:
-- zero:Zero()
```
Reason: Caching a single Angle object outside the hot path avoids memory allocation and garbage collection overhead, and it can be reset in-place using the `:Zero()` method if modifications are needed.


```lua
local addon_color = Color(255, 0, 0)
local current_color = addon_color
```
Reason: Local variables are accessed directly via virtual machine registers, which is significantly faster than nested tables that require multiple table indexing (hash map lookup) operations.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: `ply:getDarkRPVar("job")` is the official DarkRP API designed to retrieve networked player variables like job names, offering better performance and reliability than generic `GetNWString` calls.


```lua
local threshold = 100
local isWithinThreshold = vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: Using Vector:DistToSqr avoids the expensive square root operation performed by Vector:Distance, making threshold comparisons significantly faster.


```lua
for _, ent in ents.Iterator() do
    -- Code to execute on each entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator because it avoids creating a new table copy of all entities like `ents.GetAll()` does, and it returns the iterator function, state, and index directly so it does not need to be wrapped in `ipairs()`.


```lua
local ply = Entity(1) -- Target player
local radius = 500 -- Query radius in Hammer units
local entities = ents.FindInSphere(ply:GetPos(), radius)
```
Reason: ents.FindInSphere utilizes the engine's internal BSP spatial partitioning grid to quickly filter entities, making it significantly faster than iterating over all entities in Lua or using expensive PVS checks.


```lua
local function GetPlayersInSphere(pos, radius)
    local found = {}
    local radiusSqr = radius * radius
    local plys = player.GetAll()
    for i = 1, #plys do
        local ply = plys[i]
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: Iterating over `player.GetAll()` with `DistToSqr` only checks the small player pool (typically ≤ 128) instead of querying the engine's spatial partition and allocating Lua objects for thousands of map, prop, and weapon entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numerical for loop is faster because it uses specialized bytecode instructions (`FORPREP`/`FORLOOP`) that manage the counter and bounds in registers, avoiding the explicit increment and comparison overhead of a while loop.


```lua
-- Faster: Call hook.Run once per tick with the list of all players
local plys = player.GetAll()
hook.Run("TickAllPlayers", plys)

-- Listener side iterates locally using a fast loop
hook.Add("TickAllPlayers", "MyCustomLogic", function(plys)
    for i = 1, #plys do
        local ply = plys[i]
        -- Custom logic here
    end
end)
```
Reason: Calling hook.Run once avoids the significant overhead of repeated hook table lookups and function invocation wrapper logic for every player, consolidating it into a single hook call followed by a fast local Lua loop.


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

    local health = ply:Health()

    -- The three draw calls using the cached health variable
    draw.SimpleText("Health: " .. health, "DermaDefault", 50, 50, color_white)
    draw.RoundedBox(0, 50, 70, health * 2, 20, Color(200, 50, 50))
    draw.SimpleText(health .. "/100", "DermaDefault", 55, 72, color_white)
end)
```
Reason: Caching the LocalPlayer reference and storing the Health() return value in a local variable prevents repetitive, expensive Lua-to-C boundary crossings and engine queries across three separate calls within a high-frequency rendering hook.


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

-- Inside the paint loop, use the cached variable:
surface.SetDrawColor(color_white)
```
Reason: Calling the `Color()` function creates a new table on every frame, which triggers frequent garbage collection and reduces performance, whereas caching the color object outside the loop avoids table allocations.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local val = sin(i)
end
```
Reason: Localizing the function caches it on the stack, avoiding expensive hash table lookups of `math` and `sin` on each loop iteration.


```lua
local lp
local function GetLocalPlayer()
    if not lp or not lp:IsValid() then
        lp = LocalPlayer()
    end
    return lp
end
```
Reason: Caching the `LocalPlayer` entity in a local variable via lazy-loading avoids repeated expensive global table lookups and engine-level calls, leveraging Lua's fast local register access instead.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- Cosine of the maximum angle tolerance (0.7 is roughly 45 degrees)
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(-dir) > threshold
end
```
Reason: Comparing the dot products of the players' aim vectors against the normalized relative direction vector directly evaluates the cosine of the angle between them, bypassing the need for expensive inverse trigonometric functions like math.acos.


```lua
SomeHelper(ply)
```
Reason: SomeHelper(ply) is faster because it avoids the table and metatable lookup on the player object required by the colon syntax.


```lua
Msg( "Debug message\n" )
```
Reason: Msg writes a raw string directly to the engine console, bypassing the string conversion (tostring), tab-separation, and formatting overhead associated with GMod's print function.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Numeric for loops are the fastest in Garry's Mod (LuaJIT) because they avoid the function call/iterator overhead of ipairs/pairs, and the loop limit (#tbl) is evaluated only once before iteration begins.


```lua
local players = player.GetAll()
local names = {}
local count = 0

-- Fused filter and map in a single procedural loop
for i = 1, #players do
    local ply = players[i]
    if ply:isCop() then -- Filter
        count = count + 1
        names[count] = ply:Nick() -- Map
    end
end
```
Reason: Fusing filter and map operations into a single imperative loop avoids intermediate table allocations, function call overhead, and garbage collection pressure generated by functional combinator chains.


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

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

hook.Add("PlayerInitialSpawn", "RefreshPlayerCache_Join", function()
    -- Delay by 0 seconds to allow player.GetAll() to update on the next frame
    timer.Simple(0, rebuildCache)
end)

hook.Add("PlayerDisconnected", "RefreshPlayerCache_Leave", function()
    -- Delay by 0 seconds so the disconnecting player is fully removed before we rebuild
    timer.Simple(0, rebuildCache)
end)

hook.Add("Think", "OptimizedThinkHook", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Tick/Think logic here
    end
end)
```
Reason: Calling player.GetAll() generates a brand new table on every call, causing significant garbage collection overhead when run every tick; caching it and updating it asynchronously on spawn/disconnect hooks eliminates this performance bottleneck.


```lua
local playerData = {}

-- Writing data
playerData[ply] = value

-- Reading data
local value = playerData[ply]
```
Reason: Indexing a standard Lua table with the player object bypasses the player userdata's custom `__index` metamethod overhead, yielding direct table lookup speeds.


```lua
local array = { "value1", "value2", "value3" }

for i = 1, #array do
    local val = array[i]
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for-loop are stored in the contiguous array part of the Lua table and can be highly optimized and JIT-compiled, whereas string-keyed maps reside in the hash part and require traversing via pairs/next, which is significantly slower.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numeric arguments avoids the overhead of indexing table fields or invoking metatables associated with a Color object.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid) .. ";")
```
Reason: Local SQLite runs in-process on the game server's host machine, eliminating the network round-trip latency inherent in querying a remote MySQL database.


```lua
local plyMeta = FindMetaTable("Player")
local oldSteamID = plyMeta.SteamID

function plyMeta:SteamID()
    local steamID = self._steamID
    if not steamID then
        steamID = oldSteamID(self)
        self._steamID = steamID
    end
    return steamID
end
```
Reason: Overriding the Player metatable's SteamID method to retrieve and store the string on the Lua-side player object avoids the performance overhead of crossing the C++ boundary on subsequent calls.


```lua
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "some small string"
end
local result = table.concat(parts)
```
Reason: Lua strings are immutable, so repeated `..` concatenation creates a new string object and copies data at each step, leading to $O(N^2)$ complexity and heavy garbage collection, whereas `table.concat` allocates the final string buffer once and copies all elements in a single pass.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: draw.RoundedBox performs extra logic, table lookups, and texture bindings to support corner rounding, whereas surface.DrawRect is a direct, low-overhead engine call for drawing solid rectangles.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(str)
```
Reason: The `surface.*` functions are implemented directly in C++ and avoid the Lua-land overhead of `draw.*` helpers, which perform extra string parsing, alignment calculations via `surface.GetTextSize`, and multiple redraw passes (especially in outlined functions) every frame.


```lua
local tbl = { "apple", "banana", "cherry" }
local length = #tbl
```
Reason: The `#` operator is the standard, built-in Lua length operator and is the most efficient, idiomatic way to get the length of a sequential array-like table.


```lua
t = {}
```
Reason: Creating a new table with `t = {}` is a constant-time O(1) allocation, whereas `table.Empty(t)` runs in O(N) time because it iterates over the entire table in Lua to set each key to nil.


```lua
-- Creating a set where values are stored as keys mapping to true
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

-- Fast O(1) membership check
if mySet["value2"] then
    -- Value exists in the set
end
```
Reason: Key-based table lookups utilize Lua's internal hash map implementation for O(1) average-time complexity, whereas table.HasValue performs a sequential linear scan (O(N)) over the array.


```lua
local t = { x = 1, y = 2, z = 3 }
```
Reason: Defining fields directly inside the table constructor allows LuaJIT to pre-allocate the table with the correct size, avoiding the performance overhead of dynamic resizing and re-hashing that occurs when assigning fields individually after creation.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random supports non-sequential tables by iterating keys internally, whereas direct indexing with math.random and the length operator (#) is an O(1) operation.


```lua
local squared = x * x
```
Reason: Direct multiplication `x * x` is significantly faster in Lua and LuaJIT than using the exponentiation operator `x ^ 2` or calling `math.pow(x, 2)`.


```lua
for _, ply in player.Iterator() do
	-- code
end
```
Reason: player.Iterator() is the modern, optimized iterator function introduced in Garry's Mod to loop through players without allocating a new table like player.GetAll() does.


```lua
for _, ent in ipairs( ents.FindByClass( "prop_physics" ) ) do
    -- Your code here
end
```
Reason: `ents.FindByClass()` directly returns a table containing only the entities matching the specified class, avoiding the performance cost and memory allocation of building a table containing every single entity in the map (which is what `ents.GetAll()` does).


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: The `hook.Add` function is the standard Garry's Mod API for registering a callback function to a specific engine event using a unique string identifier.


```lua
if IsValid(ent) then
    -- It is now safe to call methods on ent
end
```
Reason: The IsValid function checks both that the Lua object is not nil and that the underlying C++ entity has not been removed from the server.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handler code here
end)
```
Reason: `net.Receive` is the standard Garry's Mod function for registering a callback to handle incoming network messages.


```lua
local cached_angle = Angle()

local function HotPath()
    cached_angle:Zero()
    -- Use and modify cached_angle here
end
```
Reason: Reusing a pre-allocated Angle object and resetting it with :Zero() avoids expensive userdata allocations and garbage collection overhead in frequently executed code.


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

hook.Add("HUDPaint", "MyAddonPaint", function()
    surface.SetDrawColor(config_color)
end)
```
Reason: Local variables are assigned directly to LuaJIT registers, completely bypassing the expensive hash map lookups required for nested table indexing.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system (DarkRPVars) instead of default networked strings to sync player data and reduce bandwidth overhead.


```lua
local isWithinThreshold = vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: `DistToSqr` avoids the computationally expensive square root calculation required by standard distance functions, making threshold comparisons significantly faster.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: `ents.Iterator()` is recommended over `ipairs(ents.GetAll())` because it is a stateless iterator that avoids allocating and populating a new table on every loop, significantly improving performance.


```lua
local radius = 500
local nearEnts = ents.FindInSphere(ply:GetPos(), radius)
for i = 1, #nearEnts do
    local ent = nearEnts[i]
    -- Process nearby entity
end
```
Reason: ents.FindInSphere is executed directly in the engine's C++ backend and uses spatial partitioning (octrees) to rapidly cull distant entities without iterating through the entire entity list in Lua.


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

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

    return players
end
```
Reason: Iterating `player.GetAll()` and checking `DistToSqr` is significantly faster because it only evaluates players (a small, cached array) instead of traversing the spatial partition and checking potentially thousands of entities within the sphere.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are heavily optimized in LuaJIT (which Garry's Mod uses) and avoid the overhead of manual condition checking and variable incrementing required by while loops.


```lua
-- Slower Pattern: Looping players and calling hook.Run per player
local function TickSlow()
    local plys = player.GetAll()
    for i = 1, #plys do
        hook.Run("CustomPlayerUpdate", plys[i])
    end
end
hook.Add("Tick", "TickSlowExample", TickSlow)

-- Faster Pattern: Calling hook.Run once and passing the player table
local function TickFast()
    hook.Run("CustomPlayersUpdate", player.GetAll())
end
hook.Add("Tick", "TickFastExample", TickFast)
```
Reason: Calling `hook.Run` incurs overhead from table lookups and internal hook library iterations; executing it once per tick rather than once per player significantly reduces this execution cost.


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

    local hp = ply:Health()

    draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 50, color_white)
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(50, 70, hp, 20)
    draw.SimpleText(hp .. " HP", "DermaDefault", 50, 100, color_white)
end)
```
Reason: Caching the result of LocalPlayer():Health() into a local variable avoids making multiple expensive cross-boundary C++ function calls every single frame.


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

hook.Add("HUDPaint", "OptimizedPaint", function()
    -- Use the locally cached color instead of calling Color() every frame
    surface.SetDrawColor(cached_color)

    -- Note: For pure white specifically, you can also use the built-in global constant:
    -- surface.SetDrawColor(color_white)
end)
```
Reason: Calling Color() inside a render loop allocates a new table in memory every frame which causes performance-draining garbage collection overhead, whereas caching it outside the loop (or using global constants) allocates memory only once.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local val = sin(i)
end
```
Reason: Local variable lookups are faster than global table lookups in Lua.


```lua
local ply = LocalPlayer()

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

    -- Use 'ply' directly instead of calling LocalPlayer()
end)
```
Reason: Caching the entity object locally and only refreshing it when it becomes invalid prevents the performance overhead of repeatedly crossing the C++/Lua boundary to execute the LocalPlayer() function every frame.


```lua
local function AreAimDirectionsFacing(ply1, ply2, threshold)
    -- A threshold of -0.8 means the vectors are within ~36 degrees of being perfectly opposite
    return ply1:GetAimVector():Dot(ply2:GetAimVector()) < (threshold or -0.8)
end
```
Reason: The dot product of two normalized vectors naturally returns the cosine of the angle between them, approaching -1 when they point in perfectly opposite directions, which cleanly bypasses the need for expensive trigonometric functions like math.acos.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the additional overhead of userdata metatable index lookups required by the colon syntax.


```lua
MsgN("debug message")
```
Reason: MsgN is a faster C-binding that directly outputs text with a newline, avoiding the additional Lua-side formatting and overhead of Garry's Mod's overridden print wrapper.


```lua
for i = 1, #myTable do
    local value = myTable[i]
    -- Do something with value
end
```
Reason: A numeric for loop avoids the overhead of function calls inherent to iterators like pairs or ipairs and is heavily optimized by Garry's Mod's underlying LuaJIT compiler.


```lua
local result = {}
local index = 1
for i = 1, #items do
    local item = items[i]
    if item.active then
        result[index] = item.price * 2
        index = index + 1
    end
end
```
Reason: Native loops avoid closure allocation and function call overhead per element, allowing LuaJIT to trace and compile the operations into highly optimized machine code.


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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCache_Join", function(ply)
    table.insert(activePlayers, ply)
end)

hook.Add("PlayerDisconnected", "UpdatePlayerCache_Leave", function(ply)
    table.RemoveByValue(activePlayers, ply)
end)

hook.Add("Tick", "OptimizedPlayerTick", function()
    for i = 1, #activePlayers do
        local ply = activePlayers[i]
        if IsValid(ply) then
            -- Your per-tick player logic goes here
        end
    end
end)
```
Reason: Caching the array and iterating with a numeric for-loop eliminates the per-tick table creation and iterator allocation of ipairs(player.GetAll()), drastically reducing garbage collection overhead and fully leveraging LuaJIT optimizations.


```lua
local playerData = {}

-- Write
playerData[ply] = "temporary value"

-- Read (called often)
local value = playerData[ply]
```
Reason: Indexing a standard local Lua table avoids the expensive `__index` and `__newindex` C++ metamethod lookups that occur when accessing fields directly on the Player entity object.


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

for i = 1, #items do
    local item = items[i]
    -- Do something with item
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for loop are significantly faster in LuaJIT because they access memory linearly and avoid the function call overhead and string hashing costs associated with `pairs()`.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate number arguments is faster because it avoids the overhead of table indexing required when unpacking a Color object.


```lua
local result = sql.Query("SELECT * FROM players WHERE steamid = 'STEAM_0:0:12345'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite avoids network round-trips entirely, making it inherently lower latency than remote MySQL for single-server operations.


```lua
local steamID = ply.CachedSteamID
if not steamID then
    steamID = ply:SteamID()
    ply.CachedSteamID = steamID
end
```
Reason: Accessing a Lua table field avoids the expensive C++ boundary crossing and string allocation that occurs every time the ply:SteamID() method is called.


```lua
local pieces = {}
for i = 1, 5000 do
    pieces[#pieces + 1] = "piece_" .. i
end
local largeString = table.concat(pieces)
```
Reason: table.concat pre-allocates memory for the final string in a single pass, avoiding the severe performance and garbage collection overhead of creating thousands of intermediate strings during repeated .. concatenations.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Calling `surface.DrawRect` directly bypasses the Lua function call overhead and internal radius checks of `draw.RoundedBox`, mapping more directly to the underlying engine functions.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText("Your text here")
```
Reason: surface.* functions are direct engine bindings in C++ and avoid the Lua wrapper overhead present in the draw library functions.


```lua
#my_table
```
Reason: The `#` operator is native to Lua and is the fastest, preferred method for getting the length of a sequential, non-sparse array.


```lua
t = {}
```
Reason: Assigning a new table is an O(1) operation that leaves the old table for the garbage collector, whereas table.Empty(t) is an O(N) operation that must iterate through every key to remove it.


```lua
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["orange"] = true
}

if mySet["banana"] then
    -- Value exists
end
```
Reason: Dictionary key lookups operate in O(1) time complexity, whereas table.HasValue operates in O(n) time by sequentially iterating through the entire list.


```lua
local myTable = { a = 1, b = 2, c = 3 }
```
Reason: Using the table constructor pre-allocates the necessary hash slots, avoiding the performance overhead of dynamic table resizing and rehashing that occurs when assigning fields one by one to an empty table.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random uses pairs() to iterate over all elements regardless of structure, whereas math.random(#tbl) utilizes the O(1) length operator for direct index access on sequential tables.


```lua
x * x
```
Reason: In LuaJIT (which Garry's Mod uses), direct multiplication is significantly faster than the exponentiation operator (`x ^ 2`) or `math.pow`, as it avoids the overhead of those operations and compiles down to a very fast, single machine instruction.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- do something with ply
end
```
Reason: ipairs is preferred over pairs for sequentially indexed tables like the one returned by player.GetAll() as it is more efficient and guarantees sequential iteration order.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Your code here
end
```
Reason: `ents.FindByClass` performs the class filtering internally in C++ and returns a table containing only the matching entities, avoiding the expensive memory allocation of building a table of every entity in the map like `ents.GetAll()` would do.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: The hook.Add function is the standard way to register a callback for event hooks like Think in Garry's Mod Lua.


```lua
if IsValid(ent) then
    -- Safe to call methods on ent here
end
```
Reason: The global `IsValid()` function checks that the variable is not nil and that the underlying C++ entity has not been destroyed or removed from the game world.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here
end)
```
Reason: The net.Receive function is the standard Garry's Mod API for registering a callback function to handle incoming network messages.


```lua
local cached_angle = Angle()

local function HotPath()
    cached_angle:Zero()
    -- Modify and use cached_angle here
end
```
Reason: Pre-allocating an Angle object outside the loop and resetting it with :Zero() avoids continuous memory allocations and garbage collection overhead.


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

hook.Add("HUDPaint", "MyAddonPaint", function()
    surface.SetDrawColor(myaddon_config_color)
end)
```
Reason: Local variables map directly to fast virtual registers in LuaJIT, avoiding the multiple expensive hash table lookups required when reading from nested tables.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system (DarkRPVars) instead of standard NWStrings to reduce bandwidth and correctly handle custom job titles.


```lua
local isWithinRange = vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: Using DistToSqr compares squared distances, avoiding the computationally expensive square root calculation required by the standard Distance method.


```lua
for _, ent in ents.Iterator() do
    -- Do something with 'ent' here
end
```
Reason: `ents.Iterator()` is the modern, officially recommended zero-allocation iterator that is much faster and more memory-efficient than `ipairs(ents.GetAll())` because it avoids constructing a new table on every call.


```lua
local radius = 256
local entities = ents.FindInSphere(ply:GetPos(), radius)

for i = 1, #entities do
    local ent = entities[i]
    if IsValid(ent) and ent ~= ply then
        -- process nearby entity
    end
end
```
Reason: `ents.FindInSphere` executes in C++ and leverages the Source engine's internal spatial partitioning (kd-tree), making it orders of magnitude faster than iterating all entities with distance checks in Lua.


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

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

    return players
end
```
Reason: Iterating through `player.GetAll()` using `DistToSqr` only evaluates the small number of connected players, completely bypassing the heavy table allocation and iteration overhead caused by `ents.FindInSphere` collecting every single prop, weapon, and entity in the radius.


```lua
for i = 1, n do
    -- Loop body
end
```
Reason: The numeric for loop uses specialized bytecode instructions (FORPREP and FORLOOP) that handle the increment and condition check natively, avoiding the overhead of the separate addition, comparison, and jump instructions required by a while loop.


```lua
hook.Add("Tick", "ProcessAllPlayers", function()
    local players = player.GetAll()
    hook.Run("CustomPlayerTick", players)
end)
```
Reason: `hook.Run` has internal overhead from looking up and iterating through registered listener functions, so calling it once with a table of players is significantly faster than invoking it repeatedly inside a loop for each individual player.


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

    local hp = ply:Health()

    draw.SimpleText("Health: " .. hp, "DermaDefault", 100, 100, color_white)
    draw.SimpleText("Shadow: " .. hp, "DermaDefault", 101, 101, color_black)
    surface.DrawRect(100, 120, hp, 20)
end)
```
Reason: Caching the health value in a local variable reduces expensive Lua-to-C++ boundary crossings from three down to one per frame.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cachedColor)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Creating a Color object instantiates a new table, so caching it outside the render loop prevents continuous memory allocation and expensive garbage collection overhead every frame.


```lua
local sin = math.sin
```
Reason: Local variables in Lua are stored in fast registers, bypassing the overhead of a global hash table lookup on every loop iteration.


```lua
local LocalPlayer = LocalPlayer
```
Reason: Caching the global function in a local variable prevents an expensive hash table lookup in the global environment (_G) on every call.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or -0.8
    return ply1:GetAimVector():Dot(ply2:GetAimVector()) < threshold
end
```
Reason: The dot product of two normalized vectors is highly performant and approaches -1 as the vectors point in opposing directions, entirely avoiding expensive trigonometric operations.


```lua
SomeHelper(ply)
```
Reason: Calling a standalone function directly avoids the performance overhead of the table/metatable index lookup required by the object-oriented method call syntax.


```lua
MsgN("Your debug message here")
```
Reason: MsgN is a direct C-binding that avoids the overhead of Lua's global print wrapper, which performs unnecessary formatting and tostring conversions before outputting.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Numeric for loops avoid the overhead of iterator functions like pairs and ipairs, and are heavily optimized by LuaJIT in Garry's Mod.


```lua
local function fastFilterMap(tbl, filterFunc, mapFunc)
    local result = {}
    local count = 1
    for i = 1, #tbl do
        local val = tbl[i]
        if filterFunc(val) then
            result[count] = mapFunc(val)
            count = count + 1
        end
    end
    return result
end
```
Reason: A single imperative loop with manual array indexing avoids the intermediate table allocations, closure creation, and nested function call overheads inherent in functional combinator libraries like `fn`.


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

local function UpdatePlayerCache()
    cached_players = player.GetAll()
end

hook.Add("PlayerInitialSpawn", "CachePlayers_Join", UpdatePlayerCache)
hook.Add("PlayerDisconnected", "CachePlayers_Leave", function()
    -- timer.Simple(0) is needed because the player is still in player.GetAll() during the disconnect hook
    timer.Simple(0, UpdatePlayerCache)
end)

hook.Add("Think", "Optimized_Think", function()
    -- A numeric for loop is slightly faster than ipairs
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Do something with ply here
        end
    end
end)
```
Reason: Calling `player.GetAll()` every tick creates a new table which causes significant garbage collection overhead, whereas caching it on join/leave and iterating with a numeric for loop avoids per-tick memory allocations and is computationally faster.


```lua
local playerData = {}

-- Write
playerData[ply] = "value"

-- Fast read
local data = playerData[ply]
```
Reason: Indexing a local Lua table with the player object bypasses the expensive `__index` metamethod overhead of userdata.


```lua
local fast_collection = {
    "item_one",
    "item_two",
    "item_three"
}

for i = 1, #fast_collection do
    local value = fast_collection[i]
    -- Iteration logic here
end
```
Reason: Sequential number-indexed arrays are stored in the contiguous array part of Lua's table structure, allowing a numeric for-loop to access elements directly by index without the overhead of hash lookups required by `pairs()`.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate primitive numbers avoids the table allocation and field lookup overhead associated with Color objects in a hot loop.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:0:123456'")
if result then
    PrintTable(result)
elseif result == false then
    print("SQL Error: " .. sql.LastError())
end
```
Reason: Local SQLite avoids the network round-trip overhead inherent to remote MySQL, resulting in lower latency for reads and writes on a single server.


```lua
local function GetCachedSteamID(ply)
    if not ply.CachedSteamID then
        ply.CachedSteamID = ply:SteamID()
    end
    return ply.CachedSteamID
end
```
Reason: Accessing a Lua table field is significantly faster than calling a C++ engine function because it avoids the overhead of crossing the Lua-C boundary.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece_data_" .. i
end
local largeString = table.concat(pieces)
```
Reason: Using `table.concat` builds the final string in a single pass, avoiding the O(N^2) performance cost and heavy garbage collection overhead of creating thousands of intermediate strings with the `..` operator.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Calling surface.DrawRect directly avoids the Lua function overhead of draw.RoundedBox and its internal conditional check for a radius of zero.


```lua
hook.Add("HUDPaint", "FastestTextDraw", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText("This is a fast single-line string")
end)
```
Reason: Calling the surface.* functions directly is faster because it completely bypasses the Lua-side function overhead, alignment mathematics, and newline parsing that the draw.* library wrappers perform on every frame.


```lua
#myTable
```
Reason: The `#` operator is the native, fastest, and most standard way to get the length of sequential array-like tables in Lua.


```lua
t = {}
```
Reason: Assigning a new empty table is a fast O(1) operation that leaves the old table to be garbage collected, whereas table.Empty() must iterate over every key in the table to set it to nil, taking O(N) time.


```lua
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["orange"] = true
}

if mySet["banana"] then
    -- Value exists
end
```
Reason: Direct key lookups in Lua tables provide O(1) constant time complexity, whereas table.HasValue performs an O(n) linear search.


```lua
local myTable = { a = 1, b = 2, c = 3 }
```
Reason: Defining fields within the table constructor allows Lua to pre-allocate the hash part of the table to the exact size needed, avoiding the performance overhead of multiple memory reallocations that occur when adding fields sequentially.


```lua
local randomElement = myTable[math.random(#myTable)]
```
Reason: Using the length operator (#) with math.random provides direct O(1) index access, avoiding the O(n) iteration overhead of table.Random's pairs loop.


```lua
x * x
```
Reason: Direct multiplication is faster than the exponentiation operator (`x ^ 2`) or `math.pow` in LuaJIT because it compiles to a simpler, more highly optimized instruction and avoids function call overhead.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- your code here
end
```
Reason: Using `ipairs` is more performant than `pairs` because `player.GetAll()` returns a sequentially indexed table.


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

Reason: `ents.FindByClass` queries the engine directly for entities matching the given class name, returning only those entities without you ever constructing a table of every entity in the map via `ents.GetAll()`.


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

Reason: `hook.Add` registers a callback on a named GMod hook; the first argument is the hook name (`"Think"`), the second is a unique identifier (`"MyAddon.Think"`) used to reference or remove this specific callback later, and the third is the function to run each tick.


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

Reason: `IsValid()` is the idiomatic GMod helper that returns `false` for both `nil` and `NULL` (the engine's invalid-entity sentinel), covering the common cases where `ent` was never set, was garbage-collected, or the entity was removed from the world — whereas a plain `if ent` or `ent ~= nil` check would not catch the `NULL` entity case and could cause a runtime error when a method is called on a stale reference.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- ply is the player who sent the message (server-side only; nil on client)
    local someValue = net.ReadString()
    print("[MyAddon] Received Sync from", ply, "- value:", someValue)
end)
```

Reason: `net.Receive` is the standard GMod function that binds a callback to a named net message; the callback fires automatically whenever a message with that exact name arrives, receiving the message length in bits and (on the server) the sending player as arguments.


```lua
-- Slower: allocates a new userdata object every call
local function hotPathSlow()
    local ang = Angle(0, 0, 0)
    -- use ang...
end

-- Faster: allocate once, zero it in-place each call
local _scratchAng = Angle(0, 0, 0)

local function hotPathFast()
    _scratchAng:Zero()
    local ang = _scratchAng
    -- use ang...
end
```

Reason: `Angle()` allocates a new userdata object on every call, incurring GC pressure and heap allocation cost; reusing a single pre-allocated `Angle` and calling `:Zero()` on it mutates the existing object in-place with no allocation, which is significantly cheaper in a hot path.


```lua
-- Preferred: flat local variable (module-level or upvalue)
local color = Color(255, 128, 0)

-- Read:
local c = color
```

Reason: Local variables in Lua are stored as upvalues or stack slots and accessed via direct array indexing in the VM, whereas nested table lookups (`myaddon.config.color`) require two sequential hash-table traversals plus the global `myaddon` lookup first — each a separate `GETTABLE` opcode — making a flat `local` 3–5× faster per read in tight loops.


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

Reason: `getDarkRPVar("job")` is the official DarkRP accessor for networked RP variables — it reads from DarkRP's own sync layer rather than raw NW strings, making it more reliable, version-stable, and consistent with how DarkRP itself exposes job data internally.


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

Reason: `Vector:DistToSqr()` returns the squared distance and skips the expensive `math.sqrt` call that `Vector:Distance()` performs internally, so squaring your threshold constant is far cheaper than computing a true Euclidean distance every tick.


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

Reason: `ents.Iterator()` is the GMod wiki-recommended efficient alternative to `ents.GetAll()` because it returns a stateless iterator over the internal entity list directly, avoiding the overhead of allocating and populating a new table copy on every call.


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

-- Usage
local nearby = GetNearbyEntities(player.GetByID(1), 512)
for _, ent in ipairs(nearby) do
    print(ent, ent:GetPos())
end
```

Reason: `ents.FindInSphere` performs a simple origin-distance check entirely in C++ against the engine's entity list, making it faster than `FindInPVS` (which walks BSP visibility sets) and `FindInBox` (which does the same sphere-vs-AABB test but with an extra rectangular cull step that can be slower for radius-based queries); benchmarks consistently show `FindInSphere` as the lowest-overhead option for "entities within X units of a point."


```lua
local function GetPlayersInRadius(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: `player.GetAll()` returns only the small, fixed-size player list (≤128 entries) so the loop is O(players), whereas `ents.FindInSphere` must traverse the engine's full spatial broadphase over every entity in the map before you even begin filtering — making the direct player iteration significantly cheaper when the entity count is high.


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

Reason: The numeric `for` loop is generally faster in Lua (including GLua) because the VM compiles it to dedicated `FORPREP`/`FORLOOP` opcodes that keep the counter, limit, and step in registers and branch with a single instruction, whereas a `while` loop requires explicit `i = i + 1` and `i <= n` expressions that each emit separate opcodes (ADD, LE, JMP), adding per-iteration overhead.


Answer must contain 0 through 1 candidate loops.

```lua
-- FASTER: Call hook.Run once, passing the full player table
local players = player.GetAll()

hook.Add("Think", "NotifyAllPlayers_Fast", function()
    hook.Run("OnPlayersTick", players)
end)

hook.Add("OnPlayersTick", "CustomLogic_Fast", function(plys)
    for i = 1, #plys do
        -- process plys[i]
    end
end)

-- SLOWER: Call hook.Run once per player inside the loop
hook.Add("Think", "NotifyAllPlayers_Slow", function()
    local plys = player.GetAll()
    for i = 1, #plys do
        hook.Run("OnPlayerTick", plys[i])  -- hook dispatch overhead × N players
    end
end)
```

Reason: `hook.Run` carries fixed dispatch overhead (iterating the hook table, doing string lookups, and calling each registered listener) on every invocation — calling it once and passing all players incurs that overhead only once per tick, whereas calling it N times inside a player loop multiplies that overhead by the player count each tick.


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

    draw.SimpleText("Health: " .. hp, "DermaDefault", 20, 20, Color(255, 255, 255))
    draw.RoundedBox(4, 20, 40, hp * 2, 16, Color(200, 50, 50))
    draw.SimpleText(hp .. " / 100", "DermaDefault", 20, 60, Color(255, 255, 255))
end)
```

Reason: `LocalPlayer()` performs a global table lookup and `Health()` crosses the C++/Lua boundary on every call, so caching both results in locals at the top of the frame eliminates two redundant C-side round-trips and two redundant global lookups, reducing per-frame overhead to a single call of each.


```lua
-- Cache the color once, outside the paint hook
local white = Color(255, 255, 255)

hook.Add("HUDPaint", "MyPaintHook", function()
    draw.SimpleText("Hello", "DermaDefault", 100, 100, white)
end)
```

Reason: `Color()` allocates a new table on every call; storing the result in a `local` upvalue outside the hook creates it once and reuses the same table each frame, eliminating per-frame garbage and GC pressure.


```lua
local sin = math.sin

local function computeWave(points, t)
    for i = 1, #points do
        points[i] = sin(i * t)
    end
end
```

Reason: Localizing `math.sin` into a local variable avoids the global table lookup (`_G["math"]["sin"]`) on every iteration — local variables are stored in VM registers and resolved in O(1) with a single `GETLOCAL` opcode, whereas each `math.sin` access performs two hash-table lookups (`math` in `_G`, then `sin` in the math table), which adds measurable overhead inside a tight loop.


```lua
local LocalPlayer = LocalPlayer

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

    -- Use ply freely without calling LocalPlayer() again
    local pos  = ply:GetPos()
    local vel  = ply:GetVelocity()
    local hp   = ply:Health()
end)
```

Reason: Declaring `local LocalPlayer = LocalPlayer` at the top of the file hoists the global function into a upvalue, so every subsequent call resolves through the faster local/upvalue lookup (a single array index into the function's upvalue list) instead of a full `_G` table hash-lookup each time; inside the hook the result is further stored in `ply` so the function itself is only invoked once per frame rather than once per use-site.


```lua
-- Returns true if two players are roughly facing each other.
-- threshold: dot product cutoff, e.g. 0.8 ≈ within ~37° of directly facing
local function FacingEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8

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

    -- Unit aim vectors (GetAimVector returns a normalised direction)
    local fwd1 = ply1:GetAimVector()
    local fwd2 = ply2:GetAimVector()

    -- Direction FROM ply1 TO ply2, normalised
    local to2 = (eye2 - eye1):GetNormalized()

    -- ply1 must be aiming roughly toward ply2 ...
    if fwd1:Dot(to2) < threshold then return false end

    -- ... and ply2 must be aiming roughly toward ply1
    -- (to1 == -to2, so negate the dot product)
    if fwd2:Dot(-to2) < threshold then return false end

    return true
end

-- Example usage
if FacingEachOther(ply1, ply2, 0.85) then
    print("Players are looking at each other!")
end
```

Reason: `GetAimVector()` already returns a unit vector, so two cheap dot products suffice — one checks that player 1's aim aligns with the direction *to* player 2, and one checks that player 2's aim aligns with the direction *back* to player 1 (i.e. `-to2`); both comparisons are pure multiplications and additions with no trigonometry, making this significantly faster than computing `math.acos` of the angle between aim vectors.


```lua
SomeHelper(ply)
```

Reason: In Lua, `ply:SomeHelper()` is syntactic sugar for `ply.SomeHelper(ply)`, which requires a table field lookup on `ply`'s metatable chain at runtime, whereas `SomeHelper(ply)` (a plain global or upvalue reference) skips that lookup entirely — making the free-function style faster, especially if `SomeHelper` is stored as a local upvalue (`local SomeHelper = SomeHelper`).


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

Reason: `MsgN` is a C-side function that writes directly to the console output with a newline, bypassing the overhead of `print`'s Lua-level wrapper which calls `tostring()` on every argument, concatenates them with tab separators, and routes through additional indirection — making `MsgN` (or `Msg` without a newline) meaningfully cheaper in a hot path.


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

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

Reason: The numeric `for` loop with `#t` is fastest because it avoids the overhead of iterator function calls (closures + coroutine state) that `ipairs` incurs on every step, and avoids the full hash + array traversal with unordered/unpredictable key enumeration that `pairs` uses; direct index access `t[i]` is a raw table lookup with no extra function call overhead per iteration, making it the lowest-cost option in LuaJIT (which GMod uses via Garry's Mod's Lua 5.1 with LuaJIT), where the JIT can also optimise the simple integer increment loop far more aggressively than iterator-based loops.


```lua
-- DarkRP fn library approach (slower: two passes, two intermediate tables, closure overhead)
-- local result = fn.map(fn.filter(players, fn.IsValid), fn.getName)

-- Faster: single-pass imperative loop — no intermediate tables, no closure allocation
local function filterMap(tbl, filterFn, mapFn)
    local out = {}
    local n   = 0
    for i = 1, #tbl do
        local v = tbl[i]
        if filterFn(v) then
            n = n + 1
            out[n] = mapFn(v)
        end
    end
    return out
end

-- Example: get names of valid, alive players
local names = filterMap(
    player.GetAll(),
    function(ply) return IsValid(ply) and ply:Alive() end,
    function(ply) return ply:Nick() end
)
```

Reason: `fn.filter` + `fn.map` allocates two intermediate tables and iterates the list twice, and each combinator call carries Lua closure/upvalue overhead; the single-pass loop allocates one output table, avoids all intermediate storage, and keeps every operation in a tight numeric `for` with no extra function-call indirection, which is measurably faster in LuaJIT (GMod's runtime) because the inner loop can be traced and compiled without bailing out on vararg or metatables that the fn library relies on.


```lua
-- Cached player list, rebuilt only on join/leave events
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "PlayerCache_Add", RebuildPlayerCache)
hook.Add("PlayerDisconnected", "PlayerCache_Remove", RebuildPlayerCache)

-- Populate once on script load (e.g. on a live server reload)
RebuildPlayerCache()

-- Think/Tick hook iterates the pre-built cache instead of calling player.GetAll()
hook.Add("Think", "MyFastThink", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- work with ply ...
    end
end)
```

Reason: `player.GetAll()` allocates a new table and walks an internal linked-list every call; caching the result and rebuilding it only on `PlayerInitialSpawn`/`PlayerDisconnected` (which fire at most a handful of times per session) means the Think hook pays only the cost of a numeric `for` loop over an already-allocated table, eliminating per-tick allocation and list traversal entirely.


```lua
local playerData = {}

hook.Add("PlayerInitialSpawn", "CachePlayerData", function(ply)
    playerData[ply:EntIndex()] = {
        stamina = 100,
        lastAttack = 0,
        score = 0,
    }
end)

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

-- Write
local function SetStamina(ply, val)
    playerData[ply:EntIndex()].stamina = val
end

-- Read (hot path) — plain table lookup, no metamethod chain
local function GetStamina(ply)
    return playerData[ply:EntIndex()].stamina
end
```

Reason: `ply.someField` resolves through the `Player`/`Entity` metatable's `__index` metamethod on every access (a C-side lookup into the entity's Lua table), whereas a module-local table indexed by `EntIndex()` is a direct Lua array lookup with no metamethod overhead, making it significantly faster for values read in hot loops like `Think` hooks or per-tick systems.


```lua
-- Slower: string-keyed map (hash part) — pairs() has overhead per entry
local map = { apple = 1, banana = 2, cherry = 3 }
for k, v in pairs(map) do
    _ = v
end

-- Faster: sequential number-indexed array (array part) — ipairs() / numeric for uses raw slot access
local arr = { 1, 2, 3 }
for i = 1, #arr do
    _ = arr[i]
end
```

Reason: Lua tables are split internally into an **array part** (contiguous integer keys starting at 1) and a **hash part** (everything else, including string keys). Iterating the array part with a numeric `for` loop accesses values via direct slot indexing with no hashing, no key comparison, and no iterator closure overhead, making it significantly faster than `pairs()` over a string-keyed map, which must traverse the hash part's buckets and call the `next` metamethod on each step.


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

Reason: Passing separate `r, g, b, a` integers avoids constructing (or unpacking) a `Color` table object each frame, eliminating the per-call heap allocation and the metatable lookup overhead that the Color-object overload incurs internally.


```lua
-- SQLite query using GMod's sql library (runs in-process, no network overhead)
local result = sql.Query("SELECT data FROM player_data WHERE steamid = " .. sql.SQLStr(steamid))
if result then
    print(result[1].data)
end
```

Reason: Local SQLite via the `sql` library is lower latency because queries execute in-process against a local file with no network round-trip, whereas remote MySQL incurs TCP connection overhead, network latency, and authentication handshakes on every query — making SQLite the clear winner for a single-server setup with no sync requirement.


```lua
-- Cache table: keyed by player entity index, cleared on disconnect
local steamIDCache = {}

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

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

-- Usage in your hot path:
hook.Add("Tick", "HotPathExample", function()
    for _, ply in ipairs(player.GetAll()) do
        local sid = GetCachedSteamID(ply)
        -- ... use sid freely without re-calling ply:SteamID()
    end
end)
```

Reason: `ply:SteamID()` crosses the Lua/C++ boundary on every call; caching the string result in a Lua table keyed by the stable entity index means subsequent lookups are pure Lua table reads (O(1), no C call overhead), and the `PlayerDisconnected` hook ensures stale entries are evicted so a recycled entity index can't return a wrong SteamID.


```lua
-- Slow: repeated .. creates a new string object on every iteration
local result = ""
for i = 1, 10000 do
    result = result .. "piece" .. i  -- O(n²) total allocations
end

-- Fast: collect into a table, then join once at the end
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece" .. i  -- only one allocation per piece
end
local result = table.concat(parts, "")  -- single final join
```

Reason: Each `..` on a growing string copies the entire accumulated string into a new allocation, making repeated concatenation O(n²) in time and memory; `table.concat` defers the join to one pass, making it O(n).


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

Reason: `draw.RoundedBox` is a Lua wrapper that validates arguments, sets the draw color via `surface.SetDrawColor`, and then calls `surface.DrawRect` internally — calling `surface.DrawRect` directly skips that wrapper overhead entirely, which compounds noticeably when issuing hundreds of draw calls per frame.


```lua
-- Cache everything that does not change per-frame.
local font = "DermaDefault"
local text = "Hello, world!"
local color = Color(255, 255, 255, 255)

-- Fastest: bare surface.* calls.
-- surface.SetFont / surface.SetTextColor / surface.SetTextPos are thin
-- engine calls; surface.DrawText pushes the string to the renderer directly.
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(font)
    surface.SetTextColor(color)
    surface.SetTextPos(100, 100)
    surface.DrawText(text)
end)

-- Slower alternatives shown for contrast:
-- draw.SimpleText(text, font, 100, 100, color)
-- draw.SimpleTextOutlined(text, font, 100, 100, color, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 1, color_black)
-- draw.DrawText(text, font, 100, 100, color)
```

Reason: `draw.SimpleText`, `draw.DrawText`, and especially `draw.SimpleTextOutlined` are pure-Lua wrappers that perform extra per-call work — alignment branching, outline multi-pass loops, and redundant `surface.Set*` calls even when nothing changed — whereas the raw `surface.SetFont / SetTextColor / SetTextPos / DrawText` sequence is the minimal straight-line path to the engine with no branching or extra state writes.


```lua
local myTable = {"a", "b", "c"}
local len = #myTable
```

Reason: The `#` length operator is the idiomatic and preferred way to get the length of a sequential (integer-keyed) table in Lua and Garry's Mod Lua; `table.Count` exists in GMod but iterates all keys and is intended for non-sequential/mixed tables, making `#` both faster and more appropriate for arrays.


```lua
-- Faster: reassign to a new table (O(1))
t = {}

-- Slower: table.Empty iterates every key and sets it to nil (O(n))
-- table.Empty(t)
```

Reason: `t = {}` is O(1) — it merely points the local reference at a fresh table and lets the GC collect the old one — whereas `table.Empty(t)` loops over every element setting each to `nil`, making it O(n) and proportionally slower as the table grows.


```lua
-- Slow: table.HasValue iterates the list linearly O(n)
local list = { "combine", "zombie", "headcrab" }
if table.HasValue(list, "zombie") then
    print("found")
end

-- Fast: use a hash-set (value as key) for O(1) lookup
local set = { combine = true, zombie = true, headcrab = true }
if set["zombie"] then
    print("found")
end
```

Reason: Lua tables are hash maps, so keyed lookups (`set[value]`) resolve in O(1) constant time, whereas `table.HasValue` iterates the entire sequential list until it finds a match, making it O(n) — noticeably slower as the list grows.


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

-- Slower: assign fields after {}
local t = {}
t.x = 1
t.y = 2
t.z = 3
```

Reason: The constructor form is faster because Lua (and LuaJIT used by GMod) pre-allocates the hash part of the table in a single pass when it can see the fields up front, whereas the post-assignment form triggers separate `SETTABLE`/`NEWINDEX` operations and may cause one or more internal rehashes as the table grows.


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

Reason: For sequential tables `#t` is O(1), so a direct index with `math.random` avoids the O(n) iteration that `table.Random` performs internally to handle arbitrary (non-sequential) keys.


```lua
local result = x * x
```

Reason: Multiplication (`x * x`) is faster than `math.pow(x, 2)` or `x^2` in Lua because `^` calls the C `pow()` function (which handles fractional exponents and is thus slower), while `*` is a single native multiply instruction; in a tight loop this difference compounds noticeably.


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

Reason: `ipairs` is preferred over `pairs` for array-like tables (sequential integer keys) because it iterates in order and stops at the first nil, making it both cleaner and marginally faster for the list returned by `player.GetAll()`.


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

Reason: `ents.FindByClass` queries the engine directly for entities matching the given class, so it never constructs a table of every entity in the map—unlike `ents.GetAll()` followed by a class filter.


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

Reason: `hook.Add` registers a callback for a given game event; the first argument is the hook name (`"Think"`), the second is the unique identifier (`"MyAddon.Think"`), and the third is the function to call each frame.


```lua
if IsValid(ent) then
    ent:Remove() -- or any other method
end
```

Reason: `IsValid(ent)` returns `true` only when `ent` is non-nil, is an entity (or player/NPC), and has not been removed from the game world, making it the standard guard against using a stale or NULL entity reference.


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

Reason: `net.Receive` registers a callback that fires whenever a net message with the given name arrives, providing the message length in bits and the sending player (server-side) or `nil` (client-side).


```lua
local ang_zero = Angle(0, 0, 0)          -- allocate once at load time

-- Hot path: reuse the cached angle instead of Angle(0,0,0) each call
local function GetSomeAngle()
    return ang_zero                       -- no allocation, no GC pressure
end
```

Reason: `Angle()` allocates a new userdata + metatable every call; upvaluing a single pre-built zero angle eliminates per-frame allocation and reduces garbage-collector pressure in hot paths.


```lua
local cfg_color = myaddon.config.color   -- cache the nested lookup once

local r = cfg_color.r                    -- read from the local
```

Reason: In GLua (LuaJIT), a local variable is a register access (one op), while each `.` in a nested table is a hash lookup; caching the deepest-used table into a local eliminates repeated lookups and is measurably faster on hot paths.


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

Reason: `getDarkRPVar("job")` is DarkRP's own networked-variable accessor, which stays in sync with the DarkRP job system and is the officially supported method, whereas `GetNWString("job")` bypasses DarkRP's abstraction and may break if the internal networking changes.


```lua
if a:DistToSqr(b) < threshold * threshold then
    -- within range
end
```

Reason: `DistToSqr` skips the expensive square-root that `Distance` performs, and squaring the threshold is trivial, making it the preferred method for simple range/threshold checks.


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

Reason: `ents.Iterator()` is the Garry's Mod wiki-recommended iterator for looping over all entities; it avoids the overhead of `ents.GetAll()`, which allocates a new table on every call.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 512)
for _, ent in ipairs(nearby) do
    if IsValid(ent) and ent ~= ply then
        -- work with ent
    end
end
```

Reason: `ents.FindInSphere` is implemented engine-side in C++ and consistently benchmarks as one of the fastest `FindIn*` calls for proximity queries, outperforming Lua-side distance loops and avoiding the view-dependency quirks of `FindInPVS`.


```lua
local function PlayersInRadius(pos, radius)
    local found = {}
    local r2 = radius * radius          -- compare squared distances
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= r2 then
            found[#found + 1] = ply
        end
    end
    return found
end
```

Reason: `player.GetAll()` iterates only over connected players (typically tens) instead of every entity on the map (often thousands), and `DistToSqr` avoids a per-player square-root, making this O(players) with cheaper math versus O(all entities) + filtering.


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

Reason: In GLua (LuaJIT), a numeric `for` loop is faster because the counter, limit, and step live in dedicated VM registers and the increment + boundary check compiles to a single `FORL` bytecode instruction, whereas a `while` loop requires separate variable loads, an explicit increment, and a conditional jump each iteration.


```lua
-- Pattern A: one hook.Run per tick, pass the full player table
hook.Add("Tick", "BatchNotify", function()
    hook.Run("MyCustomLogic", player.GetAll())
end)

-- Pattern B: loop players, one hook.Run per player per tick
hook.Add("Tick", "PerPlayerNotify", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("MyCustomLogic", ply)
    end
end)
```

Reason: Pattern A is faster because `hook.Run` has fixed per-call overhead (table lookup of registered listeners, function dispatch, and argument packing); calling it once with the full player list pays that cost once per tick, while Pattern B pays it N times (once per player), making the overhead scale linearly with player count.


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

    draw.SimpleText("HP: " .. hp, "DermaLarge", 50, 50, color_white)
    draw.RoundedBox(0, 50, 80, hp * 2, 20, Color(255, 0, 0))
    draw.SimpleText(hp .. "%", "DermaDefault", 50 + hp, 85, color_white)
end)
```

Reason: Caching `LocalPlayer():Health()` in a local avoids two redundant method calls per frame, since local variable access is faster than repeated table lookups and function calls in Lua.


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

hook.Add("HUDPaint", "MyHUD", function()
    -- use the pre-allocated 'white' instead of Color(255,255,255) each frame
    draw.SimpleText("Hello", "DermaDefault", 50, 50, white)
end)
```

Reason: `Color()` allocates a new table every call; hoisting it outside the paint hook creates the table once and reuses it each frame, eliminating per-frame garbage.


```lua
local sin = math.sin

for i = 1, 100000 do
    local val = sin(i * 0.01)
end
```

Reason: Caching `math.sin` in a local variable avoids repeated global (`math`) and field (`sin`) table lookups on every iteration, since local access in Lua uses faster register-based indexing.


```lua
local LocalPlayer = LocalPlayer

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

    -- use ply freely; the global lookup of LocalPlayer is already cached
    local hp = ply:Health()
    local pos = ply:GetPos()
end)
```

Reason: Lua resolves globals by walking up environment tables each call; `local LocalPlayer = LocalPlayer` at the top of the file snapshots the function reference into a local slot, which the VM accesses by fixed register index instead of a hash lookup, making every subsequent `LocalPlayer()` call faster.


```lua
--- Returns true when both players are roughly facing each other.
-- Uses dot products only – no trig calls.
-- @param threshold number  Dot-product cutoff (default -0.5 ≈ within ~120° cone).
function ArePlayersFacing(ply1, ply2, threshold)
    threshold = threshold or -0.5

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

    -- Each aim must point *toward* the other player.
    -- The direction from ply1→ply2 is compared against aim1, and vice-versa.
    local delta = ply2:GetShootPos() - ply1:GetShootPos()
    delta:Normalize()

    -- aim1 should align with delta   (dot > 0 means ply1 looks toward ply2)
    -- aim2 should align with -delta  (dot > 0 means ply2 looks toward ply1)
    -- Equivalently: aim1·delta > 0  AND  aim2·delta < 0

    -- For a tighter "staring each other down" test we also check that the
    -- two aim vectors themselves oppose each other (dot < threshold).
    return aim1:Dot(delta)  > -threshold   -- ply1 faces ply2
       and aim2:Dot(delta)  <  threshold   -- ply2 faces ply1
       and aim1:Dot(aim2)   <  threshold   -- aims oppose each other
end
```

Reason: `Vector:Dot` is a single multiply-add (no square roots, no `math.acos`), so three dot products plus a normalize is far cheaper than computing angles, and the threshold is trivially tunable without touching trig.


CLI exited without a valid strict response.