```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process entity
    end
end
```
Reason: Using ents.Iterator() allows you to iterate over all active entities using a stateless iterator, avoiding the table creation and memory overhead of ents.GetAll() or similar functions.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: The `hook.Add` function is the standard way to register callback functions to hooks in Garry's Mod Lua, using the hook name, a unique identifier, and the callback function.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    -- Safe to use ent
end
```
Reason: In Garry's Mod Lua, the `IsValid(ent)` function checks if the entity reference is not nil and that the underlying engine entity has not been destroyed.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming network message here
end)
```
Reason: net.Receive is the standard Garry's Mod library function used to register a receiver callback for net messages sent from the server to client, or vice versa.


```lua
local ZERO_ANGLE = Angle()
```
Reason: Caching a single Angle instance as a local upvalue outside the hot path avoids garbage collection overhead and memory allocations from constructing new objects on every iteration.


```lua
local setting_color = Color(255, 255, 255)
local col = setting_color
```
Reason: Local variables are accessed by index at compile-time using virtual register slots, avoiding the costly runtime hash table lookups required to resolve nested tables.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP retrieves player-specific variables (such as custom job names) using the optimized ply:getDarkRPVar internal network table instead of standard NWStrings.


```lua
local pos1 = Vector( 0, 0, 0 )
local pos2 = Vector( 0, 0, 100 )
local threshold = 150

if pos1:DistToSqr( pos2 ) < ( threshold * threshold ) then
    -- Vectors are closer than threshold
end
```
Reason: Vector:DistToSqr avoids the expensive square root operation required by Vector:Distance, making it significantly faster for threshold comparisons.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: `ents.Iterator()` is the wiki-recommended iterator because it avoids creating a new table copy on every call, unlike `ents.GetAll()`, making it significantly more efficient for performance-critical code.


```lua
local function GetNearbyEntities(ply, radius)
    return ents.FindInSphere(ply:GetPos(), radius)
end
```
Reason: ents.FindInSphere is faster and more optimized in source engine C++ benchmarks for general radial queries than ents.FindInBox or ents.FindInCone.


```lua
local function GetPlayersInSphere(position, radius)
    local players = {}
    local radiusSqr = radius * radius
    local allPlayers = player.GetAll()
    for i = 1, #allPlayers do
        local ply = allPlayers[i]
        if ply:GetPos():DistToSqr(position) <= radiusSqr then
            players[#players + 1] = ply
        end
    end
    return players
end
```
Reason: Iterating over the small list of active players via `player.GetAll()` and performing a squared-distance check avoids the high overhead of searching through thousands of map/prop entities inside the spatial partition with `ents.FindInSphere`.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric `for` loop is optimized at the engine/VM level in LuaJIT, utilizing fast bytecode instructions and register allocations without the manual variable increment and conditional checks required by a while loop.


```lua
-- Faster pattern: Call hook.Run once per tick passing all players
hook.Add("Tick", "NotifyPlayersOnce", function()
    local players = player.GetAll()
    hook.Run("NotifyPlayersTick", players)
end)
```
Reason: Calling hook.Run once avoids the CPU overhead of traversing the hook registry and calling hook functions N times (once per player) every tick.


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

    local hp = ply:Health()

    -- Draw call 1 using hp
    -- Draw call 2 using hp
    -- Draw call 3 using hp
end)
```
Reason: Caching the LocalPlayer reference and the return value of Health() in local variables avoids repeated C-boundary crossings and engine-level player/health retrievals within the same frame.


```lua
local white = Color(255, 255, 255)
-- Inside the paint loop:
-- Use the cached 'white' variable instead of recreating it
draw.SimpleText("Hello", "DermaDefault", x, y, white)
```
Reason: Calling Color() repeatedly in a high-frequency paint loop creates a new table every frame, causing unnecessary garbage collection overhead; caching the color object in a local variable outside the loop avoids this.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local y = sin(i)
end
```
Reason: Caching the global table function into a local variable avoids repeated table lookups in the hot loop, as local variable access in Lua is significantly faster.


```lua
local LocalPlayer = LocalPlayer
local lp
local function GetLocalPlayer()
    if not lp or not lp:IsValid() then
        lp = LocalPlayer()
    end
    return lp
end
```
Reason: Caching `LocalPlayer()` in a local variable avoids repeated expensive engine calls and global function lookups, while checking `:IsValid()` handles cases where the player object changes or is not yet initialized during early load.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8 -- Cosine of maximum allowed angle (e.g., 0.8 is ~36 degrees)

    local pos1 = ply1:GetShootPos()
    local pos2 = ply2:GetShootPos()

    -- Vector pointing from ply1 to ply2
    local dir = pos2 - pos1
    dir:Normalize()

    -- Both players must aim towards each other's position
    local dot1 = ply1:GetAimVector():Dot(dir)
    if dot1 < threshold then return false end

    local dot2 = ply2:GetAimVector():Dot(-dir)
    return dot2 >= threshold
end
```
Reason: Dot products of aim vectors and relative displacement vectors avoid expensive inverse trigonometric functions (`math.acos`) to determine alignment.


```lua
SomeHelper(ply)
```
Reason: SomeHelper(ply) avoids the table/metatable lookup on the player object required by the colon operator method call ply:SomeHelper().


```lua
local Msg = Msg
Msg("Debug message\n")
```
Reason: Msg is faster than print because it does not convert nil or non-string arguments automatically, does not append a newline, and caching it as a local avoids global lookup in the hot path.


```lua
local count = #t
for i = 1, count do
    local value = t[i]
    -- process value
end
```
Reason: Numeric for loops with cached table length allow LuaJIT (Garry's Mod's Lua engine) to fully JIT-compile and optimize the loop without the overhead of iterator function calls or closures associated with pairs/ipairs.


```lua
-- Standard DarkRP fn: fn.Filter(fn.Map(fn.Id, list), filterFunc) creates multiple intermediate tables and closures.
-- This approach: A single-pass procedural loop that filters and maps elements inline.
local function getActiveCPAgents(players)
    local result = {}
    local count = 0
    for i = 1, #players do
        local ply = players[i]
        -- Filter condition
        if IsValid(ply) and ply:Alive() and ply:isCP() then
            count = count + 1
            -- Map transformation
            result[count] = ply:Nick()
        end
    end
    return result
end
```
Reason: Procedural single-pass iteration eliminates the performance overhead of allocating intermediate tables and invoking multiple closures per element.


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

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

hook.Add("PlayerInitialSpawn", "RebuildPlayerCache", rebuildCache)

hook.Add("PlayerDisconnected", "RebuildPlayerCache", function()
    -- Rebuild on the next tick so the disconnected player is fully removed from player.GetAll()
    timer.Simple(0, rebuildCache)
end)

hook.Add("Think", "OptimizedThink", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Perform per-tick operations on ply here
    end
end)
```

Reason: Caching the player list on join and leave events avoids the CPU overhead of creating a new table and garbage collecting it every single tick via player.GetAll().


```lua
-- Store data in a local table keyed by the player object
local playerData = {}

-- Write
playerData[ply] = value

-- Read (highly optimized direct table lookup)
local value = playerData[ply]
```
Reason: Indexing the player object directly (e.g. `ply.field`) triggers the metatable `__index` metamethod to access the player's internal table, whereas a plain Lua table lookup keyed by the player object bypasses this metatable overhead entirely.


```lua
local tbl = { "apple", "banana", "cherry" }
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Sequential number-indexed arrays are faster because LuaJIT can optimize numeric loops and array access, avoiding hash lookups and iterator overhead.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Calling the function with separate numeric arguments (r, g, b, a) avoids the overhead of creating or unpacking a Color table/object in Lua on every frame.


```lua
local steamid = "STEAM_0:1:123456"
local result = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid) .. ";")
```
Reason: Local SQLite runs in-process on the same machine and requires no network round-trips, eliminating network latency completely.


```lua
local Player = debug.getregistry().Player
local _SteamID = Player.SteamID

-- Cache SteamIDs in a table on the player entity itself to avoid cross-lookup overhead
function Player:SteamID()
    local id = self._steamID
    if not id then
        id = _SteamID(self)
        self._steamID = id
    end
    return id
end
```
Reason: Overriding the Player metatable method to retrieve and cache the SteamID directly in the player's entity table avoids the overhead of repeated engine-level C/C++ boundary crossings.


Answer must contain 0 through 0 candidate loops.

```lua
local tbl = {}
for i = 1, 10000 do
    tbl[#tbl + 1] = "piece"
end
local result = table.concat(tbl)
```
Reason: In Lua, strings are immutable, so repeated `..` concatenation creates a new string copy every time, leading to O(N^2) time complexity and massive garbage collector overhead, whereas inserting pieces into a table and calling `table.concat` allocates the memory once and joins them efficiently in C.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, width, height)
```
Reason: `surface.DrawRect` is a direct engine-level draw call that avoids the Lua-side overhead, conditional checks, and calculations that `draw.RoundedBox` performs to handle corner rounding.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 10)
surface.DrawText("Hello World")
```
Reason: surface.SetTextPos and surface.DrawText are direct C++ engine bindings, bypassing the Lua-side overhead of draw.DrawText or draw.SimpleTextOutlined which perform extensive string formatting, position recalculations, and multiple overlapping draw calls for outlines.


```lua
local tbl = { "apple", "banana", "cherry" }
local length = #tbl
```
Reason: The length operator `#` is the standard, fastest, and most common way in Lua and Garry's Mod to get the length of a sequential table (an array).


```lua
t = {}
```
Reason: `t = {}` is a constant-time O(1) operation that allocates a new empty table, whereas `table.Empty(t)` iterates over every element to set it to `nil`, resulting in O(N) complexity which is significantly slower for large tables.


```lua
-- Slow approach: table.HasValue (O(n) search)
local list = { "apple", "banana", "cherry" }
local exists = table.HasValue(list, "banana")

-- Faster approach: Key lookup in a table/set (O(1) search)
local set = { ["apple"] = true, ["banana"] = true, ["cherry"] = true }
local exists = set["banana"] ~= nil
```
Reason: Key-based lookup in a Lua table acts as a hash map, resulting in O(1) time complexity, whereas table.HasValue performs a linear scan over the array elements resulting in O(n) time complexity.


```lua
local myTable = {
    field1 = "value1",
    field2 = "value2",
    field3 = "value3"
}
```
Reason: Defining fields directly in the table constructor allows LuaJIT to pre-allocate the correct hash and array sizes, preventing costly table rehashing and memory reallocations during subsequent assignments.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Using math.random with the length operator is faster because table.Random internally handles non-sequential tables by converting keys to a temporary table or iterating, whereas direct array indexing is a constant-time O(1) operation.


```lua
local squared = x * x
```
Reason: Direct multiplication is faster in Lua than the exponentiation operator (`x ^ 2`), which incurs the overhead of a function call.


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

```lua
for _, ply in player.Iterator() do
	-- ...
end
```
Reason: player.Iterator() is the modern, optimized iteration method in Garry's Mod that avoids the memory allocation overhead of player.GetAll().


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Code to execute on each prop_physics entity
    end
end
```
Reason: Using `ents.Iterator()` traverses the engine's internal entity list directly via a stateless iterator, avoiding the allocation of a temporary Lua table that functions like `ents.GetAll()` or `ents.FindByClass()` would create.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Code here runs every frame
end)
```
Reason: This uses Garry's Mod's standard `hook.Add` library function to register a callback function to the "Think" event hook with the custom identifier "MyAddon.Think".


```lua
if IsValid(ent) then
    -- Safe to call methods on ent
end
```
Reason: The global `IsValid` function safely checks if the entity is non-nil, exists in the game world, and is not a NULL entity, avoiding runtime errors that would occur if you directly called the `ent:IsValid()` method on a nil reference.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the net message data here
end)
```
Reason: In Garry's Mod, incoming net messages are handled using the net.Receive function, which takes the message name and a callback function to process the message content.


```lua
local temp_ang = Angle()

-- Inside the hot path, reuse the cached angle by resetting its fields in-place
temp_ang.p = 0
temp_ang.y = 0
temp_ang.r = 0
```
Reason: Instantiating a new Angle object via `Angle()` allocates memory on the Lua-to-C++ boundary, causing garbage collection overhead, whereas caching a local Angle and resetting its components in-place avoids new allocations.


```lua
local color = Color(255, 0, 0)
local currentColor = color
```
Reason: Local variables are stored in registers and accessed directly by index, completely bypassing the multiple table lookups required to resolve nested keys.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: ply:getDarkRPVar("job") is the official DarkRP API for accessing networked player variables, whereas ply:GetNWString("job") is legacy, inefficient, and no longer natively updated by modern DarkRP.


```lua
local isWithinRange = vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: Vector:DistToSqr calculates the squared distance between two vectors, avoiding the expensive square root operation required by Vector:Distance.


```lua
for _, ent in ents.Iterator() do
	-- Your code here
end
```
Reason: ents.Iterator is the wiki-recommended way to iterate over all entities in Garry's Mod because it does not allocate a new table on each call, unlike ents.GetAll.


```lua
local entities = ents.FindInSphere(ply:GetPos(), 500)
```
Reason: ents.FindInSphere is highly optimized by the Source Engine's spatial partitioning grid, making it faster than manual distance checks or ents.FindInBox for radial queries.


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

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

    return players
end
```
Reason: Iterating over the cached `player.GetAll()` table and checking squared distance is much faster because it avoids the expensive C++ engine spatial partition search that returns and allocates a table for all entity types in the area.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops in Lua use specialized virtual machine instructions and registers, avoiding the manual updates and comparisons of a while loop.


```lua
-- Call hook.Run once per tick passing the array of all players
local plys = player.GetAll()
hook.Run("OnPlayerTickBatch", plys)

-- The hook listener loops through the players internally
hook.Add("OnPlayerTickBatch", "CustomLogic", function(plys)
    for i = 1, #plys do
        local ply = plys[i]
        -- Custom logic per player
    end
end)
```
Reason: Calling hook.Run once avoids the substantial overhead of Lua-to-C hook resolution and function call overhead for every player on every tick.


```lua
local ply = LocalPlayer()
if ply:IsValid() then
    local hp = ply:Health()
    draw_call_1(hp)
    draw_call_2(hp)
    draw_call_3(hp)
end
```
Reason: Storing the player object and their health in local variables avoids redundant C-to-Lua boundary crossings and engine lookups across multiple calls.


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

-- Inside the paint hook/loop:
surface.SetDrawColor(white)
```
Reason: Calling Color() inside a paint loop instantiates a new table/object every frame, generating significant garbage collection overhead, whereas caching it in a local variable outside the loop reuses a single reference.


```lua
local sin = math.sin
-- Use 'sin' instead of 'math.sin' inside the loop
```
Reason: Localizing the function avoids two table lookups (`_G.math` and then `math.sin`) per iteration by storing the function reference in a fast local register.


```lua
local ply
local function GetLocalPlayer()
    if not IsValid(ply) then
        ply = LocalPlayer()
    end
    return ply
end
```
Reason: Caching the player entity in a local variable avoids repeated global table lookups and engine-side C-calls, falling back to LocalPlayer() only when the cache is invalid.


```lua
local function ArePlayersFacingEach Other(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- Roughly 45 degrees tolerance

    local dir = ply2:GetShootPos() - ply1:GetShootPos()
    dir:Normalize() -- Normalizes in-place to prevent object allocation

    -- ply1 must aim along dir (dot > threshold), ply2 must aim against dir (dot < -threshold)
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: Using vector dot products of the players' aim vectors against their relative displacement vector determines alignment without expensive trigonometric operations (math.acos) or garbage-collected vector allocation.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the metatable index lookup on the player userdata object required by the colon method syntax.


```lua
local Msg = Msg
Msg("Debug message\n")
```
Reason: Localizing `Msg` avoids global lookup overhead, and `Msg` writes directly to the engine console without the argument-stringification and tab-spacing overhead of `print`.


```lua
local length = #tbl
for i = 1, length do
    local val = tbl[i]
    -- process val
end
```
Reason: Numeric for loops with a cached length are compiled directly into highly optimized machine code loops by LuaJIT (which Garry's Mod runs on), bypassing the function call and iterator overhead of pairs and ipairs.


```lua
-- Traditional DarkRP fn approach:
-- local names = fn.Map(function(ply) return ply:Nick() end, fn.Filter(function(ply) return ply:isCop() end, player.GetAll()))

-- Faster approach (Direct imperative single-pass loop):
local plys = player.GetAll()
local names = {}
local count = 0

for i = 1, #plys do
    local ply = plys[i]
    if ply:isCop() then
        count = count + 1
        names[count] = ply:Nick()
    end
end
```
Reason: Direct imperative loops avoid the high overhead of Lua function calls, closure allocations, and intermediate tables generated by DarkRP's functional combinators.


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

hook.Add("PlayerInitialSpawn", "CachePlayers_Join", function(ply)
    table.insert(CachedPlayers, ply)
end)

hook.Add("PlayerDisconnected", "CachePlayers_Leave", function(ply)
    table.RemoveByValue(CachedPlayers, ply)
end)

hook.Add("Think", "CachedPlayers_Think", function()
    for i = 1, #CachedPlayers do
        local ply = CachedPlayers[i]
        -- Think logic here
    end
end)
```
Reason: Calling player.GetAll() every tick allocates a new table and bridges C++ to Lua, causing substantial garbage collection overhead, whereas a local cached table and a numeric loop avoid any allocations.


```lua
local playerData = {}

-- Writing data
playerData[ply] = "value"

-- Reading data (significantly faster as it bypasses the entity metatable)
local val = playerData[ply]

-- Clean up when the player leaves to prevent memory leaks
hook.Add("EntityRemoved", "CleanPlayerData", function(ent)
    playerData[ent] = nil
end)
```
Reason: Indexing a player entity directly triggers the Entity metatable's __index lookup, whereas indexing a local Lua table by the player object bypasses this overhead completely.


```lua
local tbl = {
    "value1",
    "value2",
    "value3"
}
```
Reason: Sequential number-indexed arrays are stored in the table's array portion, allowing extremely fast iteration using a numeric for loop or ipairs, which LuaJIT can optimize and compile much more efficiently than pairs/next traversal over hash-map parts.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numeric arguments is faster because it avoids the overhead of indexing table keys (.r, .g, .b, .a) or creating temporary Color objects that trigger garbage collection in hot rendering paths.


```lua
local steamid = "STEAM_0:1:123456"
local result = sql.Query("SELECT value FROM player_data WHERE steamid = " .. sql.SQLStr(steamid) .. ";")
```
Reason: Local SQLite executes synchronously on the same machine, eliminating the network latency, socket overhead, and handshake delays associated with a remote MySQL database connection.


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

function plyMeta:SteamID()
    local id = self._cachedSteamID
    if not id then
        id = oldSteamID(self)
        self._cachedSteamID = id
    end
    return id
end
```
Reason: Overriding the Player:SteamID method to cache the string in the player's Lua table avoids the high overhead of crossing the Lua-to-C boundary on subsequent calls.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece"
end
local result = table.concat(pieces)
```
Reason: Using `table.concat` on an array of strings avoids creating thousands of intermediate garbage strings, drastically reducing memory allocations and garbage collection overhead.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: `surface.DrawRect` is a direct C-side engine binding that bypasses the Lua-land wrapper overhead, color table unpacking, and corner-radius checks performed inside `draw.RoundedBox`.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText(str)
```
Reason: The `surface.*` functions interface directly with the engine's C++ rendering code, avoiding the Lua overhead, string parsing, and alignment calculations performed by the `draw` library wrappers.


```lua
local length = #myTable
```
Reason: The length operator (#) is the native Lua operator for retrieving the length of sequential tables, executing in O(log n) time (or O(1) in LuaJIT) compared to table.Count which runs in O(n) time by iterating through all keys.


```lua
t = {}
```
Reason: Creating a new table is a constant-time O(1) operation, whereas `table.Empty(t)` is a Lua-implemented O(N) loop that iterates through every key to set it to nil.


```lua
-- Define the set using keys for members
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

-- Fast O(1) lookup
if mySet["value2"] then
    -- Value exists
end
```
Reason: Lua tables are implemented as hash maps, allowing key lookups in O(1) constant time, whereas table.HasValue performs a linear search through the array elements, which runs in O(N) time.


```lua
local t = { x = 1, y = 2, z = 3 }
```
Reason: Defining fields directly in the table constructor allows LuaJIT to pre-allocate the table with the correct size, avoiding the overhead of multiple reallocations and rehashes that occur when assigning fields one by one to an empty table.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random supports non-sequential tables and performs an O(N) key-counting traversal, whereas using math.random with the length operator achieves O(1) direct index access.


```lua
local y = x * x
```
Reason: Direct multiplication is significantly faster in LuaJIT than the exponentiation operator (x^2) or math.pow(x, 2), which introduce overhead.


```lua
for _, ply in player.Iterator() do
	-- code
end
```
Reason: player.Iterator() is the modern, optimized iteration method in Garry's Mod that avoids the garbage collection overhead of allocating a new table with player.GetAll().


```lua
for _, ent in ents.Iterator() do
	if ent:GetClass() == "prop_physics" then
		-- Do something with the entity
	end
end
```
Reason: Using ents.Iterator() iterates directly over the engine's internal entity list, avoiding the memory allocation of a temporary table of all entities that ents.GetAll() would create.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Code here runs every frame
end)
```
Reason: Garry's Mod uses the hook.Add function to register callbacks to hooks, specifying "Think" as the hook event and "MyAddon.Think" as the unique identifier.


```lua
if IsValid(ent) then
    -- Safe to call methods on ent
end
```
Reason: The global `IsValid` function safely handles cases where the entity reference `ent` is either `nil` or a cleared `NULL` engine object, which would otherwise trigger a runtime script error if methods were called on it directly.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming network message data here
end)
```
Reason: net.Receive is the standard Garry's Mod library function used to associate a callback function with a specific net message name.


```lua
local my_angle = Angle()

-- In the hot path:
my_angle:Zero()
```
Reason: Pre-allocating a single Angle object outside the hot path and calling `:Zero()` to reset it in-place avoids the memory allocation and garbage collection overhead of constructing a new Angle object.


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

local color = cached_color
```
Reason: Local variables are stored in virtual machine registers and accessed directly, avoiding the multiple hash table lookups required to resolve nested tables.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP stores and networks player job data via its own internal system accessed via `getDarkRPVar`, which is more efficient and reliable than the engine's generic `GetNWString`.


```lua
local vecA = Vector(100, 200, 300)
local vecB = Vector(110, 200, 305)
local threshold = 50

if vecA:DistToSqr(vecB) < (threshold * threshold) then
    -- The distance between the vectors is within the threshold
end
```
Reason: Using Vector:DistToSqr avoids the computationally expensive square root operation required by Vector:Distance.


```lua
for _, ent in ents.Iterator() do
    -- Code to execute for each entity
end
```
Reason: `ents.Iterator` is the wiki-recommended efficient iterator for looping over all entities because it does not allocate a copy of the entity list table, unlike `ents.GetAll`.


```lua
local pos = ply:GetPos()
local range = 500
local mins = pos - Vector(range, range, range)
local maxs = pos + Vector(range, range, range)
local entities = ents.FindInBox(mins, maxs)
```
Reason: ents.FindInBox is faster than ents.FindInSphere because it performs a simple axis-aligned bounding box (AABB) overlap check, avoiding the more expensive distance/radius calculations.


```lua
local function GetPlayersInSphere(position, radius)
	local targets = {}
	local radiusSqr = radius * radius
	local players = player.GetAll()

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

	return targets
end
```
Reason: Iterating over player.GetAll() with a squared distance check is faster because it only evaluates the small pool of active players (typically <= 128) rather than querying the spatial partition for all entities in the area, avoiding the heavy C++-to-Lua object instantiation overhead for non-player entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops in Lua are optimized at the bytecode level using dedicated VM instructions and registers, avoiding the explicit lookup, addition, and re-assignment operations required to increment a counter in a while loop.


```lua
local players = player.GetAll()
hook.Run("TickPlayers", players)
```
Reason: Calling hook.Run once avoids the CPU overhead of repeating hook table lookups, argument handling, and listener function calls for every player.


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

    local hp = ply:Health()

    -- Draw calls using the cached health value
    draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 50, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 50, 70, color_white)
    draw.SimpleText(hp, "DermaDefault", 50, 90, color_white)
end)
```
Reason: Caching LocalPlayer() and the health value in local variables avoids repeated C++ boundary transitions and function lookups across multiple calls in the same frame.


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

hook.Add("HUDPaint", "DrawBox", function()
    surface.SetDrawColor(color_white)
    surface.DrawRect(50, 50, 100, 100)
end)
```
Reason: Calling Color() inside a loop repeatedly instantiates new table objects, causing garbage collection overhead, whereas caching the color in a local variable outside the loop allows reusing the same reference.


```lua
local sin = math.sin

for i = 1, 1000000 do
    local y = sin(i)
end
```
Reason: Localizing the function caches the lookup, replacing a table index operation (`math.sin`) with a fast local register lookup in Lua's virtual machine.


```lua
local lp
local function GetLocalPlayer()
    if not IsValid(lp) then
        lp = LocalPlayer()
    end
    return lp
end
```
Reason: Caching the player entity in a local variable avoids repeated global table lookups and C-function overhead, while the `IsValid` check ensures the player is fully initialized before caching.


```lua
local function ArePlayersFacingEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7
    local dir = ply2:GetShootPos() - ply1:GetShootPos()
    dir:Normalize()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: Using the dot product of the players' aim vectors against the normalized vector between them allows checking if they are facing each other using cheap vector arithmetic, avoiding expensive math.acos calls.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` is faster because `ply:SomeHelper()` requires indexing the Player userdata to look up the function in its metatable, which incurs a performance penalty compared to a direct function call.


```lua
local Msg = Msg
Msg( "debug\n" )
```
Reason: Localizing `Msg` avoids global namespace lookups and bypasses `print`'s internal overhead of string conversion, tab separation, and newline formatting.


```lua
for i = 1, #myTable do
    local value = myTable[i]
    -- process value
end
```
Reason: Garry's Mod uses LuaJIT, which optimizes numeric for loops into highly efficient machine instructions, bypassing the generator function call overhead associated with ipairs and pairs.


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

for i = 1, #plys do
    local ply = plys[i]
    if ply:Team() == TEAM_CITIZEN then
        count = count + 1
        names[count] = ply:Nick()
    end
end
```
Reason: A single-pass numeric loop avoids closure allocations, function call overhead, and intermediate table creations inherent in functional combinators.


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

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

hook.Add("PlayerInitialSpawn", "CachePlayers_Join", updateCache)
hook.Add("PlayerDisconnected", "CachePlayers_Leave", function()
    -- timer.Simple(0) ensures the disconnected player is fully removed from player.GetAll() before rebuild
    timer.Simple(0, updateCache)
end)

hook.Add("Think", "CachedThinkExample", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Process player logic here
    end
end)
```
Reason: Caching the player list and rebuilding it only on join/leave events avoids allocating a new table and querying the C++ engine via player.GetAll() up to 66+ times per second, significantly reducing garbage generation and CPU overhead.


```lua
local playerData = {}

-- Store data
playerData[ply] = value

-- Read data (fast direct lookup bypassing metatable search)
local value = playerData[ply]

-- Clean up to prevent memory leaks when players disconnect
hook.Add("PlayerDisconnected", "CleanupFastData", function(ply)
    playerData[ply] = nil
end)
```
Reason: Indexing the player object directly triggers GMod's custom `__index` metamethod which routes through C-side lookups, whereas a local Lua table indexed by the player object bypasses all metatable overhead for direct, near-instantaneous reads.


```lua
local my_table = { "value1", "value2", "value3" }
```
Reason: Sequential number-indexed arrays store values contiguously in the table's array portion, allowing the LuaJIT compiler to optimize iteration via numeric for loops or ipairs, whereas string-keyed maps store values in the hash portion which requires slower hash-chain traversal using pairs or next.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numeric arguments is faster because it avoids the overhead of Color object allocation, table dereferencing, and GC churn in hot rendering hooks.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamID) .. ";")
```
Reason: Local SQLite runs directly in-process on the game server's host machine, eliminating the network latency, TCP overhead, and connection handshake delays associated with query requests to a remote MySQL server.


```lua
local plyMeta = debug.getregistry().Player
local oldSteamID = plyMeta.SteamID

function plyMeta:SteamID()
    local cached = self._steamID
    if not cached then
        cached = oldSteamID(self)
        self._steamID = cached
    end
    return cached
end
```
Reason: Caching the SteamID directly on the Player entity's Lua table avoids the overhead of crossing the Lua-to-C boundary on repeated calls.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece"
end
local result = table.concat(pieces)
```
Reason: Using table.concat avoids creating thousands of intermediate string allocations in memory, preventing garbage collection overhead and reducing time complexity from quadratic to linear.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect calls the engine's C++ rendering functions directly, bypassing the Lua-implemented overhead and parameter checks of the draw.RoundedBox wrapper.


```lua
surface.SetFont( "DermaDefault" )
surface.SetTextColor( 255, 255, 255, 255 )
surface.SetTextPos( x, y )
surface.DrawText( text )
```
Reason: surface.DrawText and its setup functions are direct C++ engine bindings, whereas the draw library functions are Lua-implemented wrappers that introduce overhead from string splitting, alignment calculations, and multiple draw calls for outlines.


```lua
local tbl = { "apple", "banana", "cherry" }
local length = #tbl
```
Reason: The native `#` operator is the fastest and standard Lua method to get the length of a sequential, one-indexed array-like table.


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


```lua
-- Fast lookup table (set) representation
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

-- Check if value exists (O(1) time complexity)
if mySet["value2"] then
    -- Value exists
end
```
Reason: Key-based lookup in a table uses a hash map operation with O(1) average time complexity, whereas table.HasValue performs a linear scan with O(N) time complexity.


```lua
local tbl = {
    field1 = "value1",
    field2 = "value2",
    field3 = "value3"
}
```
Reason: Putting fields in the table constructor allows the LuaJIT VM to pre-allocate the table with the correct hash/array size in a single allocation, avoiding the performance overhead of repeated resizing and rehashing that occurs when assigning fields one by one to an empty table.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Using math.random with the length operator `#` is an O(1) lookup, whereas table.Random is designed for non-sequential tables and incurs O(N) traversal overhead.


```lua
local squared = x * x
```
Reason: Direct multiplication is faster and more easily optimized by the LuaJIT compiler than using the exponentiation operator (x ^ 2) or math.pow.


```lua
for _, ply in player.Iterator() do
	-- ply represents the player object
end
```
Reason: player.Iterator() is the modern and optimized method in Garry's Mod that avoids allocating a new table copy on every call, unlike player.GetAll().


CLI exited without a valid strict response.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback code here
end)
```
Reason: hook.Add is the standard Garry's Mod function used to attach callbacks to engine events.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: The IsValid() global function checks both that the reference is not nil and that its underlying C++ entity object has not been destroyed by the engine.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Your handler logic here
end)
```
Reason: `net.Receive` is the built-in function provided by the Garry's Mod net library to register a callback for when a specific network message string is received.


```lua
local cachedAngle = Angle()

local function MyHotPath()
    cachedAngle:Zero()
    -- Use cachedAngle safely here without allocating a new object
end
```
Reason: Caching an Angle object outside the loop and resetting it with `:Zero()` prevents continuous object allocation and significantly reduces garbage collection overhead.


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

hook.Add("HUDPaint", "MyAddonDraw", function()
    surface.SetDrawColor(myaddon_config_color)
end)
```
Reason: Local variables are resolved via fast register accesses in LuaJIT, whereas nested table fields require slower hash map lookups on every read.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own custom networking system to sync variables like job and money, which is significantly more bandwidth-efficient than standard NWStrings.


```lua
local isWithinRange = vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: DistToSqr avoids the computationally expensive square root calculation that is performed when calculating actual distance, making it much faster for simple threshold comparisons.


```lua
for _, ent in ents.Iterator() do
    -- Do something with 'ent'
end
```
Reason: `ents.Iterator()` is a stateless C-side iterator that avoids the overhead of allocating and garbage-collecting a new table on every call, making it significantly faster and more memory-efficient than `ipairs(ents.GetAll())`.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 250)
for i = 1, #nearby do
    local ent = nearby[i]
    if IsValid(ent) then
        -- Process entity
    end
end
```
Reason: ents.FindInSphere uses the engine's internal C++ spatial partitioning (BSP/octree) to quickly cull distant entities, making it vastly faster than iterating through ents.GetAll() and calculating distances in Lua.


```lua
local function GetPlayersInRadius(pos, radius)
    local found = {}
    local radiusSqr = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: Iterating the globally cached `player.GetAll()` table and using `DistToSqr` is much faster because it avoids the C++ spatial partition query and prevents the expensive Lua table allocation/garbage collection overhead caused by returning all entities in the sphere.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric `for` loop is generally faster because the loop counter, limit, and step are managed internally by optimized VM instructions, avoiding explicit incrementing and condition checking in Lua space.


```lua
hook.Add("Tick", "NotifyPlayersBatch", function()
    local plys = player.GetAll()
    hook.Run("CustomPlayerTick", plys)
end)
```
Reason: Calling hook.Run once minimizes the expensive internal table lookups and function dispatch overhead of the hook library, which scales poorly when executed per-player every single tick.


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

    local health = ply: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: Caching the result of LocalPlayer():Health() into a local variable avoids the performance overhead of repeatedly crossing the Lua-to-C++ boundary within the same frame.


```lua
local myColor = Color(255, 255, 255) -- or simply use the built-in color_white

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(myColor)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Caching the Color object outside the render hook prevents allocating a new table every frame, avoiding unnecessary garbage collection overhead and potential stuttering.


```lua
local sin = math.sin
for i = 1, 10000 do
    local val = sin(i)
end
```
Reason: Local variable lookups in Lua are faster than table lookups since locals are accessed by index in a register rather than by a hash map lookup.


```lua
local ply

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

    -- Use 'ply' here directly instead of calling LocalPlayer()
end)
```
Reason: Caching the local player entity object and only re-fetching it if it evaluates as invalid avoids the overhead of repeatedly calling the C++ bound `LocalPlayer()` function every frame.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(-dir) > threshold
end
```
Reason: The dot product of normalized vectors yields the cosine of the angle, allowing a fast threshold comparison that avoids expensive math.acos calls while verifying both aim vectors align with the line connecting the players.


```lua
SomeHelper(ply)
```
Reason: Calling a function directly avoids the overhead of metatable index lookups associated with the colon operator.


```lua
MsgN("Debug line")
```
Reason: MsgN directly calls the engine's print function, bypassing the additional formatting overhead and type checks of the global print function.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Garry's Mod runs on LuaJIT, which heavily optimizes numeric for loops over sequential arrays and avoids the function call overhead required by pairs and ipairs iterators.


```lua
local result = {}
local index = 1
for i = 1, #inputList do
    local item = inputList[i]
    if item.isValid then
        result[index] = item.value * 2
        index = index + 1
    end
end
```
Reason: A single imperative loop avoids intermediate table allocations, closure creation, and function call overhead, allowing LuaJIT to fully trace and optimize the execution.


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

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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCacheJoin", RefreshPlayerCache)
hook.Add("PlayerDisconnected", "UpdatePlayerCacheLeave", RefreshPlayerCache)

-- Initialize cache in case script loads after players have joined
RefreshPlayerCache()

hook.Add("Tick", "OptimizedPlayerTick", function()
    for i = 1, numPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Perform tick logic for ply here
        end
    end
end)
```
Reason: Calling `player.GetAll()` every tick creates a new table and causes significant garbage collection overhead; updating the cache only on connect/disconnect events avoids this continuous memory allocation while allowing a highly optimized numerical loop.


```lua
local playerData = {}

-- Store data
playerData[ply] = value

-- Read data frequently
local myData = playerData[ply]
```
Reason: Accessing a standard Lua table avoids the __index metamethod overhead and C++ boundary crossing inherent to userdata entity objects.


```lua
local collection = {
    "item1",
    "item2",
    "item3"
}

for i = 1, #collection do
    local value = collection[i]
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for-loop are much faster in LuaJIT than string-keyed maps using pairs() because they avoid hash table lookups and allow for highly optimized, predictable memory access.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate number primitives is faster in LuaJIT because it completely avoids the overhead of table allocation (if created inline) and the internal C++ field lookups required to extract values from a Color object.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345678' LIMIT 1")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite has lower latency because it operates directly on the local server disk, completely avoiding the network overhead and round-trip time required to communicate with a remote MySQL database.


```lua
local function GetCachedSteamID(ply)
    local id = ply.CachedSteamID
    if id then return id end

    id = ply:SteamID()
    ply.CachedSteamID = id
    return id
end
```
Reason: Retrieving a stored value from a Lua table bypasses the overhead of crossing the C/C++ boundary that occurs when calling engine functions.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "some_small_string_piece_" .. i
end
local final_string = table.concat(pieces)
```
Reason: table.concat allocates memory once for the final string, avoiding the massive performance overhead of allocating and garbage-collecting thousands of intermediate string objects caused by repeated .. concatenation.


```lua
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect avoids the Lua wrapper overhead, color table lookup, and conditional branch checks present in draw.RoundedBox.


```lua
hook.Add("HUDPaint", "DrawFastText", function()
    surface.SetFont("Default")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(50, 50)
    surface.DrawText("Fastest drawing approach")
end)
```
Reason: Calling the underlying C-bound `surface.*` functions directly bypasses the additional Lua-side overhead, table lookups, and function calls introduced by wrapper libraries like `draw`.


```lua
#table_name
```
Reason: The `#` operator is the standard, built-in, and most performant way in Lua 5.1/LuaJIT (which GMod uses) to get the length of a sequential array.


```lua
t = {}
```
Reason: Reassigning to a new table is an O(1) operation that simply drops the reference to the old table, avoiding the O(n) iteration overhead of `table.Empty()`.


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

if mySet["apple"] then
    -- Value exists
end
```
Reason: Using the values as table keys allows for O(1) hash map lookups, whereas table.HasValue performs a slower O(n) sequential search through the list.


```lua
local tbl = { x = 1, y = 2, z = 3 }
```
Reason: Using the table constructor allows Lua to pre-allocate the exact size needed for the fields, avoiding expensive reallocations and rehashing that occur when assigning elements to an initially empty table.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Using the length operator (#) with math.random provides O(1) direct access, avoiding the O(N) iteration and counting overhead of table.Random.


```lua
local result = x * x
```
Reason: In LuaJIT, direct multiplication avoids the function call and exponentiation overhead of `math.pow(x, 2)` or `x^2`, compiling to a single fast CPU multiplication 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: Using `ipairs` is faster and more optimal than `pairs` when iterating over sequentially indexed tables like the one returned by `player.GetAll()`.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- your code here
end
```
Reason: `ents.FindByClass` filters entities on the C++ side and only returns a table of the matching entities, avoiding the performance overhead of building a table of every entity in the map like `ents.GetAll` would.


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


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: `IsValid()` checks if the reference is non-nil and ensures the underlying C++ entity object has not been removed from the engine.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Your handler code here
end)
```
Reason: net.Receive is the standard function in Garry's Mod used to register a callback that executes when a network message with the specified name is received.


```lua
local tempAngle = Angle()

local function MyHotPathFunction()
    tempAngle:Zero()
    -- Modify and use tempAngle here instead of calling Angle()
end
```

Reason: Reusing a pre-allocated variable and resetting it with `:Zero()` avoids the expensive C++ userdata memory allocation and subsequent garbage collection overhead of constructing a new Angle object every time.


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

hook.Add("HUDPaint", "MyAddonDraw", function()
    surface.SetDrawColor(myaddon_config_color)
end)
```
Reason: Local variables are stored in registers and accessed via direct array indexing in the Lua VM, entirely bypassing the expensive string hashing and hash table lookups required for nested global tables.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: Garry's Mod networks a player's team index natively, so looking up the name locally via the engine's team library is much faster and avoids wasting networked string limits.


```lua
vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: It calculates the squared distance, avoiding the computationally expensive square root operation required to find the exact distance.


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
end
```
Reason: ents.Iterator() is the wiki-recommended zero-allocation iterator, making it significantly faster and more memory-efficient than creating a new table with ents.GetAll().


```lua
local nearby_ents = ents.FindInSphere(ply:GetPos(), 500)
```
Reason: ents.FindInSphere leverages the Source engine's spatial partitioning to rapidly query entities within a radius without iterating through all entities on the server.


```lua
local function GetPlayersInRadius(pos, radius)
    local found = {}
    local radiusSqr = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            found[#found + 1] = ply
        end
    end
    return found
end
```
Reason: Iterating over the relatively small list of all players and checking their squared distance avoids the expensive engine overhead of querying the spatial partition for every entity type and generating a large intermediate table.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric `for` loop utilizes dedicated, highly optimized virtual machine opcodes for iteration, avoiding the manual incrementation and condition checking overhead required by a `while` loop.


```lua
hook.Add("Tick", "NotifyAllPlayers", function()
    local plys = player.GetAll()
    hook.Run("CustomPlayerTick", plys)
end)
```
Reason: hook.Run has internal overhead from string lookups and iterating over listeners, so calling it once with a table of players is significantly faster than invoking that overhead for every single player in a loop.


```lua
hook.Add("HUDPaint", "OptimizedHUD", function()
    local ply = 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", 51, 51, color_black)
    draw.SimpleText("Health: " .. hp, "DermaDefault", 52, 52, color_white)
end)
```
Reason: Caching the health value in a local variable eliminates the overhead of repeatedly executing C++ engine function calls (LocalPlayer and Health) multiple times in a single frame.


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

hook.Add("HUDPaint", "MyOptimizedPaintLoop", function()
    surface.SetDrawColor(cachedColor)
end)
```
Reason: Caching the Color object outside the hook prevents a new table from being allocated every frame, which avoids unnecessary memory usage and garbage collection overhead.


```lua
local sin = math.sin
for i = 1, 100000 do
    local result = sin(i)
end
```
Reason: Local variables in Lua are stored in fast virtual machine registers, avoiding the overhead of expensive hash table lookups required by global variables like `math.sin` during every iteration.


```lua
local ply

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

    -- Use 'ply' here instead of calling LocalPlayer()
end)
```
Reason: Caching the player entity in a local variable and only updating it when it becomes invalid avoids the overhead of crossing the Lua-to-C++ boundary on every frame or tick.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: The dot product computes the cosine of the angle between two normalized vectors using basic arithmetic, allowing for a fast threshold check without the performance overhead of trigonometric functions like math.acos.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the overhead of metatable string key lookups associated with method syntax.


```lua
MsgN("debug line")
```
Reason: MsgN directly outputs to the console and avoids the internal formatting, argument iteration, and tab-separation overhead that the global print function performs.


```lua
for i = 1, #myTable do
    local val = myTable[i]
end
```
Reason: A numeric for loop is the fastest in Garry's Mod (LuaJIT) because it completely avoids the function call and iterator overhead associated with pairs and ipairs.


```lua
local result = {}
local count = 1
for i = 1, #inputList do
    local val = inputList[i]
    if val > 0 then -- filter condition
        result[count] = val * 2 -- map transformation
        count = count + 1
    end
end
```
Reason: A single `for` loop avoids the function call overhead, closures, and intermediate table allocations inherent to DarkRP's `fn` combinators.


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

hook.Add("PlayerInitialSpawn", "PlayerCache_Join", function(ply)
    cached_count = cached_count + 1
    cached_players[cached_count] = ply
end)

hook.Add("PlayerDisconnected", "PlayerCache_Leave", function(ply)
    for i = 1, cached_count do
        if cached_players[i] == ply then
            table.remove(cached_players, i)
            cached_count = cached_count - 1
            break
        end
    end
end)

hook.Add("Think", "OptimizedTickHook", function()
    for i = 1, cached_count do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Tick logic for player here
        end
    end
end)
```
Reason: Maintaining a sequential table updated only on join and leave avoids the overhead of table creation in player.GetAll() and allows the use of a highly optimized numeric for-loop instead of ipairs() every single tick.


```lua
local playerData = {}

-- Writing
playerData[ply] = value

-- Reading
local data = playerData[ply]
```
Reason: Local Lua table lookups avoid the expensive __index metamethod and C-boundary overhead incurred when accessing properties on Garry's Mod userdata objects.


```lua
local fastArray = {
    "first_value",
    "second_value",
    "third_value"
}
```
Reason: Sequential number-indexed arrays are stored in the contiguous array part of Lua's table structure, making iteration with a numeric for loop or `ipairs` significantly faster than the hash map lookups required for string keys.


```lua
surface.SetDrawColor( 255, 255, 255, 255 )
```
Reason: Passing separate numbers directly to the C API avoids the overhead of Lua table indexing and metatable lookups associated with passing a Color object.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:1234567'")
if result then
    PrintTable(result)
elseif result == false then
    print("SQL Error: " .. sql.LastError())
end
```
Reason: Local SQLite reads and writes directly to the local disk, completely eliminating the network round-trip latency and socket overhead required to communicate with a remote MySQL server.