Uses IsValid for entity/object validity.


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

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

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

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

hook.Add("Think", "CachedThinkExample", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Perform per-tick operations on ply here
        end
    end
end)
```
Reason: Caching player.GetAll() in a local table and updating it only on player connection/disconnection hooks avoids allocating a new table and garbage collecting it every single tick, while using a standard `for i = 1, #cachedPlayers` loop is faster than `ipairs`.


```lua
local playerData = {}

-- Set value
playerData[ply] = value

-- Get value
local value = playerData[ply]
```
Reason: Storing data in a local Lua table indexed directly by the player object bypasses the __index and __newindex metamethod lookups on the entity's userdata wrapper.


```lua
local tbl = { "value1", "value2", "value3" }
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Sequential number-indexed arrays store elements in a contiguous array memory block, allowing the LuaJIT VM to perform highly optimized linear indexing via a basic numeric loop, whereas string-keyed maps reside in the hash portion of the table and require expensive hash lookups and iterator overhead via pairs().


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Calling `surface.SetDrawColor` with separate numeric arguments (r, g, b, a) is faster in a hot draw path because it avoids creating or dereferencing a Lua `Color` table/object structure and prevents garbage collection overhead.


```lua
-- Local SQLite query style in Garry's Mod
local results = sql.Query("SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamID) .. ";")
if results == false then
    print("SQL Error: " .. sql.LastError())
end
```
Reason: Local SQLite avoids network round-trip latency entirely, making it significantly faster for single-server reads and writes than a remote MySQL database.


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

function Player:SteamID()
    local id = self._steamid
    if id == nil then
        id = GetSteamID(self)
        self._steamid = id
    end
    return id
end
```
Reason: Overriding the Player metatable method to cache the SteamID directly on the player entity object avoids repeated C++ boundary calls on subsequent invocations.


Answer must contain 0 through 0 candidate loops.

```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "some_string_piece"
end
local result = table.concat(pieces)
```
Reason: table.concat accumulates strings in a table and performs a single allocation at the C level, avoiding the overhead of creating and garbage-collecting thousands of temporary intermediate string objects generated by repeated .. operations.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `surface.DrawRect` is a direct engine binding that avoids the overhead of table lookups, argument checking, and internal rounding logic present in `draw.RoundedBox`.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText("Hello World")
```
Reason: surface.DrawText and its surface.* helpers are direct C-engine bindings, whereas draw.* functions are higher-level Lua wrappers that introduce performance overhead by parsing alignments, splitting strings, and calling surface functions internally.


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


```lua
t = {}
```
Reason: `t = {}` is a constant-time O(1) operation that simply allocates a new empty table, whereas `table.Empty(t)` uses a Lua-land loop to set every key to `nil`, which is an O(N) operation and gets progressively slower as the size of the table increases.


```lua
-- O(1) Lookup Table (Set) approach
local weaponSet = {
    ["weapon_357"] = true,
    ["weapon_pistol"] = true,
    ["weapon_smg1"] = true
}

-- Fast check
local isAllowed = weaponSet["weapon_pistol"]
```
Reason: Using table keys as a set allows O(1) constant-time lookups via hash-map indexing, whereas table.HasValue performs a slow O(N) linear search through all list elements.


```lua
-- Faster way: Put them in the table constructor
local myTable = {
    x = 1,
    y = 2,
    z = 3
}
```
Reason: Putting fields in the table constructor allows LuaJIT to pre-allocate the table with the correct size in a single allocation, preventing costly rehashing and resizing that occurs when assigning fields one by one after initialization.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random traverses the table using pairs() to support non-sequential keys, making it O(N), whereas indexing with math.random and the length operator (#) is O(1).


```lua
local sq = x * x
```
Reason: Local variable multiplication `x * x` is significantly faster in LuaJIT than `x^2` or calling a function like `math.pow(x, 2)`, as it translates directly to a single CPU instruction without function call overhead or power-of exponentiation math.


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

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


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- your code here
    end
end
```
Reason: Using `ents.Iterator()` avoids allocating a new Lua table containing all entities in the map, unlike `ents.GetAll()`, and allows filtering by class inside the loop.


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

end)
```
Reason: Using hook.Add registers the function to the "Think" event under the unique string identifier "MyAddon.Think".


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: The global `IsValid(ent)` function checks if the reference is non-nil, is a valid entity, and has not been removed from the game, avoiding nil-pointer errors that occur when calling `ent:IsValid()` on a nil value.


```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 associate a callback function with a specific net message identifier.


```lua
local temp = Angle()

-- In the hot path:
temp:Zero()
```
Reason: Reusing a pre-allocated Angle object and resetting it with `:Zero()` avoids heap allocation and garbage collection overhead in the hot path.


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


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: `ply:getDarkRPVar("job")` is the official DarkRP API, which is optimized for DarkRP's internal networking and correctly retrieves custom job names changed via the `/job` command.


```lua
local isWithinThreshold = vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: Using DistToSqr avoids the expensive square root calculation required by Distance, making threshold checks significantly faster.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: `ents.Iterator()` is the Garry's Mod wiki-recommended iterator to visit all entities efficiently as it avoids the table allocation overhead of `ents.GetAll()`.


```lua
local function getNearbyEntities(ply, radius)
    return ents.FindInSphere(ply:GetPos(), radius)
end
```
Reason: ents.FindInSphere is implemented in C++ and uses the engine's internal spatial partitioning to quickly filter entities, making it one of the fastest built-in spatial queries in Garry's Mod.


```lua
local function GetPlayersInSphere(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 capped list of active players via `player.GetAll()` and checking their squared distance with `DistToSqr` avoids querying the entire server's spatial partition (which contains thousands of props/entities) and eliminates costly square root operations.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric `for` loops in Lua utilize dedicated virtual machine instructions (`FORPREP` and `FORLOOP`) and are heavily optimized by LuaJIT's compiler, making them significantly faster than `while` loops which require manual counter increment, comparison, and branching instructions.


```lua
local players = player.GetAll()
hook.Run("TickAllPlayers", players)
```
Reason: Calling hook.Run once avoids the CPU overhead of repeatedly looking up and invoking hook listeners for every individual player.


```lua
local hp = LocalPlayer():Health()
draw.SimpleText(hp, "DermaDefault", 10, 10, color_white)
draw.SimpleText(hp, "DermaDefault", 10, 30, color_white)
draw.SimpleText(hp, "DermaDefault", 10, 50, color_white)
```
Reason: Caching the result of `LocalPlayer():Health()` in a local variable avoids multiple expensive Lua-to-C boundary calls within the same frame.


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

-- Use cachedColor inside the paint loop instead of Color(255, 255, 255)
```
Reason: Calling Color() repeatedly in a paint loop creates a new table every frame, generating garbage collector overhead, whereas caching it in a local variable avoids allocations.


```lua
local sin = math.sin
```
Reason: Caching the global function into a local variable before the loop avoids repeated table lookups in the global environment and table indexing operations.


```lua
local ply
local function GetLocalPlayer()
	if not IsValid(ply) then
		ply = LocalPlayer()
	end
	return ply
end
```
Reason: Caching the player entity locally once it becomes valid avoids the overhead of repeated global table lookups and C-side entity retrieval.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, tolerance)
    tolerance = tolerance or 0.707 -- Cosine of 45 degrees (default tolerance)
    local dir = ply2:GetShootPos() - ply1:GetShootPos()
    dir:Normalize() -- Modifies vector in-place, avoiding extra allocations

    local dot1 = ply1:GetAimVector():Dot(dir)
    local dot2 = ply2:GetAimVector():Dot(dir)

    -- ply1 must look towards ply2 (dot1 > tolerance)
    -- ply2 must look towards ply1 (dot2 < -tolerance)
    return dot1 > tolerance and dot2 < -tolerance
end
```
Reason: The dot product of normalized vectors represents the cosine of the angle between them, allowing direction comparisons using simple threshold checks while completely avoiding the computationally expensive math.acos function.


```lua
SomeHelper(ply)
```
Reason: Direct function calls are faster because they avoid the table and metatable lookup overhead required to resolve method syntax.


```lua
local Msg = Msg

-- Inside hot path:
Msg("debug\n")
```
Reason: `Msg` is a direct C-side engine function that bypasses the automatic string conversion, tab separation, and formatting overhead that `print` performs, and localizing the function avoids repeated global table lookups.


```lua
local count = #tbl
for i = 1, count do
    local val = tbl[i]
    -- process val
end
```
Reason: Numeric for loops with a cached length avoid the overhead of iterator function calls and allow LuaJIT to compile the loop into highly optimized direct array accesses.


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

for i = 1, #players do
    local ply = players[i]
    if ply:isCP() then
        count = count + 1
        cpNames[count] = ply:Nick()
    end
end
```
Reason: A single-pass procedural loop avoids the allocation of intermediate tables and eliminates the overhead of nested function calls associated with functional combinators in Lua.


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

hook.Add("PlayerInitialSpawn", "SyncCachedPlayers_Join", function(ply)
    table.insert(cachedPlayers, ply)
end)

hook.Add("PlayerDisconnected", "SyncCachedPlayers_Leave", function(ply)
    table.RemoveByValue(cachedPlayers, ply)
end)

hook.Add("Think", "MyThinkHook", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Your per-tick code here using the cached players table
    end
end)
```
Reason: Calling player.GetAll() every tick allocates a new table and repeatedly references C++ objects in Lua, which triggers frequent garbage collection and degrades performance; caching the table and mutating it only during join/leave events eliminates this allocation overhead.


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

-- To write data:
player_cache[ply] = value

-- To read data (extremely fast):
local value = player_cache[ply]
```
Reason: Indexing a weak-keyed Lua table with the player object avoids the expensive metatable lookup (__index) of the player userdata while preventing memory leaks upon disconnect.


```lua
local tbl = { "A", "B", "C" }

for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Sequential number-indexed arrays store elements contiguously in the table's array part, enabling extremely fast iteration via a numeric for loop that LuaJIT compiles directly to machine code, whereas string-keyed maps must reside in the hash part and be traversed using pairs.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numeric arguments avoids table indexing overhead and temporary Color object allocations, which reduces GC pressure in hot draw loops.


```lua
local steamID = "STEAM_0:0:123456"
local result = sql.Query("SELECT points FROM player_data WHERE steamid = " .. sql.SQLStr(steamID) .. ";")
if result == false then
    print("SQL Error: " .. sql.LastError())
elseif result then
    local points = tonumber(result[1].points)
end
```
Reason: Local SQLite executes queries in-process and writes directly to the local disk, avoiding the network round-trip latency and connection overhead inherent in communicating with a remote MySQL server.


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

function plyMeta:SteamID()
    local id = self._steamID
    if not id then
        id = rawSteamID(self)
        self._steamID = id
    end
    return id
end
```
Reason: Storing the SteamID on the player object's Lua table avoids the overhead of repeated Lua-to-C boundary crossings.


```lua
local parts = {}
for i = 1, 10000 do
    parts[i] = "chunk"
end
local result = table.concat(parts)
```
Reason: table.concat avoids the overhead of creating and garbage-collecting thousands of temporary intermediate strings by buffering the pieces in a table and joining them in a single operation.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Using surface.DrawRect directly avoids the Lua function call overhead, parameter validation, and conditional checks performed inside the draw.RoundedBox wrapper.


```lua
surface.SetFont( "Default" )
surface.SetTextColor( 255, 255, 255, 255 )
surface.SetTextPos( x, y )
surface.DrawText( text )
```
Reason: Low-level surface.* functions are direct C-bindings, whereas draw.DrawText and draw.SimpleTextOutlined are higher-level Lua wrappers that introduce performance overhead by parsing alignments, splitting strings, and executing additional calculations before ultimately calling the surface.* functions.


```lua
local length = #myTable
```
Reason: The `#` operator is the standard, built-in Lua length operator and is the most efficient way to get the length of a sequential, array-like table.


```lua
t = {}
```
Reason: Reassigning to a new table is an O(1) operation, whereas table.Empty(t) iterates over all elements to set them to nil, which is an O(N) operation and significantly slower for large tables.


```lua
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

if mySet["value2"] then
    -- Found
end
```
Reason: Key-based lookup uses Lua's internal hash table matching, which operates in O(1) constant time, whereas table.HasValue performs a sequential scan over array values in O(N) linear time.


```lua
local t = {
    x = 1,
    y = 2,
    z = 3
}
```
Reason: Putting fields in the table constructor allows LuaJIT to pre-allocate the table with the correct size in a single operation, avoiding multiple re-allocations and re-hashing steps that occur when assigning fields one-by-one to an empty table.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Directly indexing the table using `math.random` with the length operator `#` is an O(1) operation, whereas `table.Random` traverses the entire table to handle arbitrary non-sequential keys, resulting in O(N) complexity and garbage collection overhead.


```lua
local squared = x * x
```
Reason: Local multiplication is the fastest arithmetic operation in LuaJIT, bypassing the overhead of the exponentiation operator or math library function calls.


```lua
for _, ply in player.Iterator() do
    -- ply:Ping(), ply:Nick(), etc.
end
```
Reason: player.Iterator() is the modern and highly optimized way to loop through players in Garry's Mod, replacing pairs(player.GetAll()) to avoid unnecessary table allocations and garbage collection overhead.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Process each prop_physics entity here
end
```
Reason: Using `ents.FindByClass` retrieves a filtered table containing only the specified class directly from the engine, avoiding the overhead of creating or filtering a table of every entity in the map.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Minimal callback body
end)
```
Reason: In Garry's Mod, hook.Add is the standard API function used to register a callback function to a hook event like "Think" with a unique string identifier.


```lua
if IsValid(ent) then
    -- Safe to use ent
end
```
Reason: The global `IsValid` function safely handles cases where `ent` is `nil` or a NULL entity without throwing a Lua error, unlike calling the `:IsValid()` method directly.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle incoming net message data here
end)
```
Reason: net.Receive is the standard Garry's Mod Lua function used to register a receiver callback for a net message name.


```lua
local myAngle = Angle()

-- Inside the hot path:
myAngle:Zero()
```
Reason: Reusing a cached local Angle and calling `:Zero()` resets its values in-place, avoiding new object allocations and reducing garbage collection overhead in the hot path.


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

-- Read
local drawColor = myaddon_color
```
Reason: Local variables are stored in virtual machine registers and accessed directly by index, completely avoiding the multiple hash map lookups required by nested tables.


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

-- Avoid
local jobName = ply:GetNWString("job")
```
Reason: `ply:getDarkRPVar("job")` utilizes DarkRP's optimized custom networking system, which is faster and avoids the performance overhead and potential synchronization issues of GMod's native `GetNWString`.


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


```lua
for _, ent in ents.Iterator() do
    -- code
end
```
Reason: `ents.Iterator()` is preferred over `ents.GetAll()` because it iterates over entities without allocating a new table on every call, significantly reducing garbage collection overhead in performance-sensitive environments.


```lua
local entities = ents.FindInSphere(ply:GetPos(), radius)
```
Reason: ents.FindInSphere queries the engine's internal spatial partitioning (BSP tree/leaf system) in C++, avoiding the overhead of iterating over all entities in Lua.


```lua
local function GetPlayersInSphere(pos, radius)
    local players = {}
    local radiusSqr = radius * radius
    for _, ply in player.Iterator() do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            players[#players + 1] = ply
        end
    end
    return players
end
```
Reason: player.Iterator() and DistToSqr avoid the overhead of ents.FindInSphere querying all map entities (props, weapons, etc.) and allocating tables/Lua objects for them, checking only the active player list instead.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are optimized at the Lua VM level using dedicated bytecode instructions, making them faster than while loops which require manual variable increments and conditional checks.


```lua
-- Faster Pattern: Call hook.Run once per tick, passing the array of all players
local players = player.GetAll()
hook.Run("TickAllPlayers", players)
```
Reason: Calling hook.Run once avoids the significant overhead of repeated table lookups, string evaluations, and call overhead inside the Garry's Mod hook library for every individual player on every tick.


```lua
local ply = LocalPlayer()

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

    local hp = ply:Health()
    -- Use the local variable 'hp' in the three draw calls here
end)
```
Reason: Caching the player reference and the health integer in local variables avoids the overhead of repeated Lua-to-C boundary transitions and table lookups on every frame.


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

hook.Add("HUDPaint", "FasterPaintExample", function()
    surface.SetDrawColor(color_white)
    surface.DrawRect(50, 50, 100, 100)
end)
```
Reason: Caching the color object in a local variable outside the paint loop prevents the overhead of creating and garbage collecting a new color table on every frame.


```lua
local sin = math.sin
```
Reason: Caching the function in a local variable avoids repeated table lookups for the global table 'math' and the key 'sin' by accessing it directly from the Lua stack.


```lua
local ply
local function GetLocalPlayer()
    if ply and ply:IsValid() then return ply end
    ply = LocalPlayer()
    return ply
end
```
Reason: Caching the player object in a local upvalue avoids the overhead of repeated global lookups and C-boundary transitions of LocalPlayer(), while dynamically initializing it handles cases where the player is not yet valid during early load.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- ~45 degrees FOV threshold
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: Vector dot products compare alignment using fast multiply-add operations, bypassing the CPU-intensive inverse trigonometric functions needed to find the actual angle.


```lua
SomeHelper(ply)
```
Reason: Calling a direct function is faster because it avoids the overhead of a metatable lookup on the player userdata object.


```lua
MsgN("Debug message")
```
Reason: MsgN is faster than print because it writes directly to the console output stream without the overhead of print's string conversion, tab separation, and formatting logic.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Numeric for loops compile to direct, low-overhead bytecode instructions that are highly optimized by LuaJIT in Garry's Mod, completely avoiding the iterator function overhead of ipairs and pairs.


```lua
-- Faster single-pass imperative loop replacing: fn.Map(fn.GetName, fn.Filter(fn.Self.Alive, player.GetAll()))
local players = player.GetAll()
local aliveNames = {}
local count = 0

for i = 1, #players do
    local ply = players[i]
    if ply:Alive() then -- Filter
        count = count + 1
        aliveNames[count] = ply:Nick() -- Map
    end
end
```
Reason: Direct imperative loops avoid the excessive closure allocations, intermediate table creations, and function call overhead inherent in the fn library, allowing LuaJIT to fully optimize the execution path.


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

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

hook.Add("PlayerInitialSpawn", "CachePlayers_Join", function()
    timer.Simple(0, rebuildCache)
end)

hook.Add("PlayerDisconnected", "CachePlayers_Leave", function()
    timer.Simple(0, rebuildCache)
end)

hook.Add("Think", "OptimizedPlayerThink", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Perform your per-tick player logic here
    end
end)
```
Reason: Calling player.GetAll() and ipairs every tick allocates a new table and iterator, causing garbage collection overhead, whereas caching the table on player join/leave hooks using timer.Simple(0) avoids per-tick allocation and ensures the cache updates only when players actually transition.


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

-- Write
playerData[ply] = value

-- Read
local value = playerData[ply]
```
Reason: Indexing a local Lua table with the player object as a key avoids the overhead of the Player metatable __index and __newindex metamethods, while a weak-keyed table prevents memory leaks when players disconnect.


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

for i = 1, #array do
    local value = array[i]
    -- Process value
end
```
Reason: Sequential number-indexed arrays iterated via a numeric for loop allow LuaJIT to compile the traversal into direct array-offset operations in machine code, bypassing the hash-table lookup and iterator overhead of pairs/next used for string-keyed maps.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing separate numeric arguments avoids the performance overhead of indexing a table or allocating a new Color object, reducing garbage collection pressure in hot draw loops.


```lua
local steamID = sql.SQLStr(ply:SteamID64())
local result = sql.Query("SELECT * FROM player_stats WHERE steamid = " .. steamID)
if result == false then
    ErrorNoHalt("SQLite Error: " .. sql.LastError() .. "\n")
end
```
Reason: Local SQLite runs in-process and writes directly to the server's local disk (sv.db), completely eliminating the network round-trip overhead and connection latency required by a remote MySQL database.


```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 metatable method to cache the SteamID on the player's Lua table prevents repeated expensive Lua-to-C boundary crossings.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "piece"
end
local result = table.concat(pieces)
```
Reason: table.concat is faster because it builds the final string in a single allocation at the C level, whereas repeated .. concatenation creates new intermediate string objects for every operation, generating excessive garbage and triggering frequent garbage collection cycles.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Bypasses the Lua-level overhead of `draw.RoundedBox`, which performs argument checks and conditional logic before eventually calling the lower-level C-backed `surface.DrawRect`.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(x, y)
surface.DrawText("text")
```
Reason: The surface methods compile directly to C++ engine calls, avoiding the Lua-side wrapper overhead, alignment/size calculations, and multiple drawing passes performed by the draw library.


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


```lua
table.Empty(t)
```
Reason: table.Empty(t) is faster because it recycles the existing table, avoiding garbage collection (GC) pressure and the CPU overhead of reallocating and resizing memory when the table is repeatedly repopulated.


```lua
-- Instead of: table.HasValue(list, val) which is O(N)
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true,
}

if mySet[val] then
    -- Value exists in the set
end
```
Reason: Using values as keys allows for O(1) hash table lookup, whereas table.HasValue performs an O(N) linear search.


```lua
local tbl = { x = 1, y = 2, z = 3 }
```
Reason: Putting fields directly in the table constructor allows LuaJIT to pre-allocate the table with the exact required hash/array sizes, avoiding the performance 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` is designed for arbitrary tables and must retrieve all keys (which is $O(N)$ and allocates memory), whereas indexing with `math.random(#tbl)` is $O(1)$ and avoids allocations.


```lua
local squared = x * x
```
Reason: Multiplying the variable by itself is significantly faster than using the exponentiation operator `x^2` or calling `math.pow(x, 2)`, as it avoids function call and power-operation overhead by compiling directly to a single CPU multiplication instruction.


```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 creating a temporary table copy compared to player.GetAll().


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Do something with ent
end
```
Reason: `ents.FindByClass` filters the entity list internally in C++ and only allocates a table containing the matching entities, avoiding the massive overhead and memory allocation of using `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback code here
end)
```
Reason: hook.Add is the standard Garry's Mod function used to bind a callback to a specific engine event hook like Think.


```lua
if IsValid(ent) then
    -- It is safe to call methods on ent here
end
```
Reason: The IsValid() function safely checks both that the variable is not nil and that the underlying C++ entity object hasn't been removed from the game world by the engine.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here
end)
```
Reason: In Garry's Mod Lua, the `net.Receive` function is used to register a callback that executes whenever a specific network message is received from the server (or client).


```lua
local temp_angle = Angle()

local function HotPathFunction()
    temp_angle:Zero()
    -- Mutate and use temp_angle here instead of calling Angle()
end
```

Reason: Pre-allocating the Angle object once and resetting its values in-place with `:Zero()` avoids the expensive C++ userdata allocation and garbage collection overhead that comes with calling `Angle()` repeatedly.


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

hook.Add("HUDPaint", "MyAddon_Draw", function()
    surface.SetDrawColor(myaddon_config_color)
end)
```
Reason: Local variables use fast register-based opcodes, whereas global variables and nested tables require comparatively slower hash-based dictionary lookups.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: It relies on the built-in Garry's Mod team system which networks a single integer (the team index) instead of redundantly transmitting a full string for every player, significantly reducing network bandwidth.


```lua
local isClose = vec1:DistToSqr(vec2) <= (threshold * threshold)
```
Reason: DistToSqr avoids the computationally expensive square root operation required to calculate the exact distance, making it significantly faster for simple threshold checks.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: `ents.Iterator()` is significantly more efficient than `ipairs(ents.GetAll())` because it iterates directly over the engine's internal entity list without allocating and garbage collecting a new Lua table every time the loop runs.


```lua
local function GetEntitiesNearPlayer(ply, radius)
    local entsNear = ents.FindInSphere(ply:GetPos(), radius)
    for i = 1, #entsNear do
        local ent = entsNear[i]
        -- Process entity
    end
    return entsNear
end
```
Reason: ents.FindInSphere utilizes the engine's internal spatial partitioning to quickly return entities within a radius without iterating over all entities in the map.


```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
            table.insert(players, ply)
        end
    end
    return players
end
```
Reason: Iterating the small `player.GetAll()` table and calculating squared distance avoids the heavy overhead of querying the physics engine's spatial partition for all entities.


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

Reason: Numeric for loops in LuaJIT are highly optimized with single internal instructions for bounds checking and incrementing, whereas while loops require manual variable manipulation overhead.


```lua
hook.Add("Tick", "ProcessAllPlayers", function()
    local players = player.GetAll()
    hook.Run("CustomPlayerTick", players)
end)
```
Reason: Calling hook.Run has a baseline performance overhead for table lookups and function iteration, so invoking it once per tick is vastly faster than paying that overhead for every single player per tick.


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

    local hp = ply:Health()

    draw.SimpleText("Health 1: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("Health 2: " .. hp, "DermaDefault", 10, 30, color_white)
    draw.SimpleText("Health 3: " .. hp, "DermaDefault", 10, 50, color_white)
end)
```
Reason: Caching the result of LocalPlayer():Health() in a local variable prevents the expensive overhead of crossing the C/Lua boundary multiple times per frame.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cached_color)
    surface.DrawRect(50, 50, 100, 100)
end)
```
Reason: Caching the Color object outside the paint loop prevents unnecessary table allocations and reduces garbage collection overhead every frame.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local result = sin(i)
end
```
Reason: Local variable lookups in Lua are significantly faster than global table lookups because they bypass hash table checks and are registered directly as bytecode registers, which LuaJIT heavily optimizes.


```lua
local LocalPlayer = LocalPlayer

hook.Add("Think", "OptimizedPlayerLogic", function()
    local ply = LocalPlayer()

    if not IsValid(ply) then return end

    -- Use 'ply' here instead of calling LocalPlayer() multiple times
    local pos = ply:GetPos()
    local health = ply:Health()
end)
```
Reason: Localizing the `LocalPlayer` function avoids expensive global table lookups, and caching its result in a local variable within the scope prevents redundant function calls.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    -- threshold is a cosine value (e.g., 0.8 is roughly a 36-degree cone)
    threshold = threshold or 0.8

    local dir = (ply2:EyePos() - ply1:EyePos()):GetNormalized()

    local ply1LookingAt2 = ply1:GetAimVector():Dot(dir) > threshold
    local ply2LookingAt1 = ply2:GetAimVector():Dot(-dir) > threshold

    return ply1LookingAt2 and ply2LookingAt1
end
```
Reason: The vector dot product calculates the cosine of the angle between normalized vectors, bypassing the expensive `math.acos` function by comparing the result directly against a cosine threshold.


```lua
SomeHelper(ply)
```
Reason: Direct function calls are faster because they avoid the table and metatable __index lookup overhead required by object-oriented method call syntax.


```lua
MsgN("debug information")
```
Reason: MsgN is a direct C++ binding to the engine's message system, which avoids the string formatting and global environment overhead of Lua's standard print function.


```lua
local len = #myTable
for i = 1, len do
    local value = myTable[i]
end
```
Reason: A numeric for loop avoids the function call overhead of iterators and is heavily optimized by LuaJIT.


```lua
local result = {}
local index = 1
local players = player.GetAll()

for i = 1, #players do
    local ply = players[i]
    if IsValid(ply) and ply:Alive() then -- Filter operation
        result[index] = ply:Nick()       -- Map operation
        index = index + 1
    end
end
```
Reason: Fusing the filter and map steps into a single imperative loop avoids the closure overhead and intermediate table allocations of the `fn` library, allowing Garry's Mod's LuaJIT to effectively compile and optimize the trace.


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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCache_Join", function(ply)
    if not table.HasValue(cachedPlayers, ply) then
        table.insert(cachedPlayers, ply)
    end
end)

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

hook.Add("Tick", "OptimizedTickExample", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Perform per-player tick logic here
        end
    end
end)
```
Reason: Calling `player.GetAll()` generates a new table every time it is invoked, causing unnecessary memory allocation and garbage collection overhead on every tick, whereas a cached sequential array updated only on join/leave allows for much faster iteration without the memory cost.


```lua
local playerData = {}

-- Write
playerData[ply] = "some_value"

-- Read (faster)
local val = playerData[ply]
```
Reason: Storing data in a plain Lua table using the player object as a key bypasses the slow C++ `__index` metamethod lookups required when reading fields directly from Player userdata objects.


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

for i = 1, #fast_array do
    local value = fast_array[i]
end
```
Reason: Sequential number-indexed arrays with a numeric for-loop read directly from the table's array part, bypassing hash map lookup overhead and benefiting heavily from LuaJIT optimization compared to pairs().


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numeric arguments is faster because it avoids table allocation and the overhead of field lookups within the engine's C++ bindings.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:1234567'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite reads from and writes directly to a local file, completely avoiding the network overhead and round-trip delays associated with remote MySQL connections.


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

local function GetFastSteamID(ply)
    local id = steamIDCache[ply]
    if not id then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end
```
Reason: Reading from a local weak-keyed Lua table avoids the costly Lua-to-C++ context switch and userdata metamethod lookups associated with repeatedly calling `ply:SteamID()`.


```lua
local parts = {}
for i = 1, 10000 do
    parts[i] = "piece_" .. i
end
local finalString = table.concat(parts)
```
Reason: `table.concat` is significantly faster because it calculates the total required length and allocates memory exactly once, avoiding the O(N^2) overhead of repeatedly allocating and garbage-collecting intermediate strings created by the `..` operator.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Calling the underlying surface functions directly avoids the overhead of the draw.RoundedBox Lua wrapper function and its internal conditional checks for rounded corners.


```lua
hook.Add("HUDPaint", "DrawFastText", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Fast single-line text")
end)
```
Reason: Direct surface.* functions are faster because they are direct C++ bindings that bypass the extra Lua function call overhead, argument validation, and alignment calculations present in the draw.* wrapper functions.


```lua
#my_table
```
Reason: The `#` operator is native to Lua and is the most performant way to get the length of a sequential (array-like) table without unnecessary iteration overhead.


```lua
t = {}
```
Reason: Assigning a new empty table is an O(1) operation that is significantly faster than `table.Empty(t)`, which incurs O(N) overhead by iterating through and deleting every key individually.


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

if mySet["apple"] then
    -- Value exists
end
```
Reason: Table key indexing provides O(1) lookup time, whereas table.HasValue performs an O(n) sequential iteration through the list.


```lua
local t = { field1 = 1, field2 = 2 }
```
Reason: Using the table constructor pre-allocates the table to the correct size, avoiding the expensive memory reallocations and rehashing that occur when adding fields to an initially empty table.


```lua
local randomElement = myTable[math.random(#myTable)]
```
Reason: `table.Random` uses `pairs` and `table.Count` resulting in O(N) time complexity, whereas `math.random(#myTable)` allows for direct O(1) index access on sequential tables.


```lua
local y = x * x
```
Reason: Direct multiplication avoids the overhead of function calls or exponentiation operators and is highly optimized by LuaJIT.


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 more efficient and appropriate than `pairs` because `player.GetAll()` returns a sequentially indexed table, not a dictionary.


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

Reason: `ents.FindByClass` performs the class filtering directly in the engine's C++ side and returns a table containing only the matched entities, avoiding the massive memory allocation and garbage collection overhead of building a table of every single entity in the map like `ents.GetAll()` does.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: The hook.Add function is the standard API in Garry's Mod for attaching custom callback functions to engine events like Think.


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


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handler logic here
end)
```
Reason: The `net.Receive` function is the built-in Garry's Mod API for hooking a callback to an incoming network message by its identifier.


```lua
local cached_angle = Angle()

local function HotPath()
    cached_angle:Zero()
    -- Use cached_angle
end
```
Reason: Reusing a pre-allocated Angle object and resetting it with :Zero() avoids the expensive C++ memory allocation and garbage collection overhead caused by repeatedly calling Angle() every time.


```lua
local myaddon_config_color = Color(255, 255, 255)
local current_color = myaddon_config_color
```
Reason: Local variables are accessed directly by a fast register index in the Lua VM, completely avoiding the expensive hash map lookups required for nested tables or global variables.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own custom, optimized networking system (DarkRPVars) which is significantly more efficient than standard Garry's Mod NWStrings.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- Vectors are closer than the threshold distance
end
```
Reason: Using DistToSqr is faster than Distance because it avoids the computationally expensive square root operation.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: ents.Iterator() is the wiki-recommended approach because it is a stateless, allocation-free iterator that completely avoids the expensive table creation and subsequent garbage collection overhead caused by ents.GetAll().


```lua
local function GetEntitiesNearPlayer(ply, radius)
    local pos = ply:GetPos()
    local offset = Vector(radius, radius, radius)
    return ents.FindInBox(pos - offset, pos + offset)
end
```
Reason: ents.FindInBox is widely benchmarked as faster than ents.FindInSphere because it utilizes highly optimized AABB (Axis-Aligned Bounding Box) checks against the engine's spatial partition tree, avoiding expensive distance calculations.


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

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

    return result
end
```
Reason: Iterating over the small `player.GetAll()` table using `DistToSqr` is much faster than `ents.FindInSphere` because it bypasses scanning the spatial partition tree containing thousands of irrelevant game entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops use dedicated opcodes in LuaJIT that handle the counter and condition internally, avoiding the overhead of manual variable increments and conditional jumps required by a while loop.


```lua
hook.Add("Tick", "ProcessAllPlayers", function()
    local players = player.GetAll()
    hook.Run("CustomLogicAllPlayers", players)
end)
```
Reason: Calling hook.Run has internal iteration and lookup overhead, so invoking it once per tick with the players table avoids multiplying this overhead by the player count.


```lua
local hp = LocalPlayer():Health()
draw.SimpleText(hp, "DermaDefault", 10, 10, color_white)
draw.SimpleText(hp, "DermaDefault", 10, 30, color_white)
draw.SimpleText(hp, "DermaDefault", 10, 50, color_white)
```
Reason: Caching the result in a local variable avoids the performance overhead of redundant global lookups and C++ method calls every frame.


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

hook.Add("HUDPaint", "OptimizedPaint", function()
    surface.SetDrawColor(drawColor)
    -- Alternatively, use the built-in global: color_white
end)
```
Reason: Caching the Color object outside the loop prevents continuous table allocations and reduces garbage collection overhead every frame.


```lua
local sin = math.sin
for i = 1, 10000 do
    local result = sin(i)
end
```
Reason: Local variables in Lua are stored in virtual machine registers, making them significantly faster to access than performing a table lookup for math.sin on every iteration.


```lua
local cached_ply

local function GetLocalPlayer()
    if IsValid(cached_ply) then return cached_ply end
    cached_ply = LocalPlayer()
    return cached_ply
end
```
Reason: Caching the player entity in a local variable avoids the recurring overhead of a global environment lookup and a C-side engine function call, while checking `IsValid` ensures the reference is safely refreshed if it becomes invalid.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    local dir = (ply2:EyePos() - ply1:EyePos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: The vector dot product directly returns the cosine of the angle between two normalized vectors, allowing you to check against a threshold (e.g., 0.8) and bypass the computationally expensive math.acos function entirely.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the expensive metatable lookup overhead associated with userdata objects in Garry's Mod.


```lua
MsgN("debug line here")
```
Reason: `MsgN` is a direct engine binding that avoids the overhead of GMod's `print` function, which is a Lua wrapper that iterates over all arguments, calls `tostring` on them, and concatenates the results before printing.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: In Garry's Mod (which uses LuaJIT), a numeric for loop avoids the function call overhead of iterators and is the most easily optimized and compiled by the JIT compiler.


```lua
local result = {}
local index = 1
local players = player.GetAll()

for i = 1, #players do
    local ply = players[i]
    if ply:IsAdmin() then
        result[index] = ply:Nick()
        index = index + 1
    end
end
```
Reason: Procedural loops with manual array indexing avoid closure allocations and intermediate table creations, allowing Garry's Mod's LuaJIT compiler to fully trace and optimize the code without garbage collection overhead.


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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCacheJoin", function(ply)
    table.insert(cachedPlayers, ply)
end)

hook.Add("PlayerDisconnected", "UpdatePlayerCacheLeave", function(ply)
    for i, p in ipairs(cachedPlayers) do
        if p == ply then
            table.remove(cachedPlayers, i)
            break
        end
    end
end)

hook.Add("Tick", "OptimizedTickHook", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Your tick logic here
        end
    end
end)
```
Reason: Calling `player.GetAll()` every tick creates a new table that causes significant garbage collection overhead, whereas updating a cached sequential array only when players join or leave eliminates this per-tick allocation cost.


```lua
local playerData = {}

hook.Add("PlayerInitialSpawn", "InitTemporaryData", function(ply)
    playerData[ply] = { someField = "value" }
end)

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

-- Read access is now a direct table lookup rather than a userdata metatable lookup
-- local val = playerData[ply].someField
```
Reason: Indexing a plain local Lua table directly avoids the slow `__index` metatable lookups and C-API boundary crossings that occur when reading fields from a userdata Player object.


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

for i = 1, #fast_array do
    local value = fast_array[i]
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for loop read directly from the contiguous array portion of the table, avoiding hash lookup overhead and allowing LuaJIT to optimize the iteration significantly better than `pairs` on a string-keyed map.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing primitive number arguments avoids the performance overhead of Lua table indexing associated with Color objects.


```lua
local result = sql.Query("SELECT money FROM player_data WHERE steamid = 'STEAM_0:0:123456'")
if result then
    print(result[1].money)
end
```
Reason: Local SQLite operates directly on the server's local file system, avoiding the network round-trip overhead and latency associated with remote MySQL connections.


```lua
local function GetCachedSteamID(ply)
    local sid = ply.CachedSteamID
    if not sid then
        sid = ply:SteamID()
        ply.CachedSteamID = sid
    end
    return sid
end
```
Reason: Lua table lookups on the entity object are significantly faster than repeatedly calling the C++ function `ply:SteamID()` across the Lua-C boundary.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "small_piece"
end
local large_string = table.concat(pieces)
```
Reason: table.concat allocates memory once for the final combined string, avoiding the O(N^2) memory reallocation and copying overhead caused by Lua's immutable strings during repeated concatenation.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: Directly using the C++ bound `surface` API bypasses the execution overhead of the Lua `draw` library wrapper and its internal corner radius conditional checks, while also allowing you to hoist the color setup outside of your rendering loop for even greater performance.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Hello World")
```
Reason: Calling `surface.*` methods directly is faster because it executes native C bindings, avoiding the extra Lua wrapper overhead, table allocations, and argument validation found in `draw.SimpleText` and `draw.DrawText`.


```lua
local length = #myTable
```
Reason: The `#` operator is the native built-in method for sequential tables in Lua 5.1, providing O(log n) performance compared to the O(n) iteration overhead of GMod's `table.Count`.


```lua
t = {}
```
Reason: Reassigning to a new table is an O(1) operation that avoids the O(N) iteration overhead of `table.Empty`, which uses `pairs` internally.


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

if mySet["apple"] then
    -- The value exists in the set
end
```
Reason: Key lookups in Lua tables use an O(1) hash map approach, which is significantly faster than `table.HasValue` performing an O(n) linear search through an array.


```lua
local myTable = {
    name = "Player",
    health = 100,
    armor = 50
}
```
Reason: Defining fields directly in the table constructor allows Lua/LuaJIT to pre-allocate the correct amount of memory in a single step, avoiding the performance overhead of resizing and rehashing the table with each individual assignment.


```lua
local element = tbl[math.random(#tbl)]
```
Reason: table.Random iterates through the table using pairs() which takes O(n) time to support associative keys, whereas math.random(#tbl) directly indexes the table in O(1) time.


```lua
local result = x * x
```
Reason: Direct multiplication avoids the overhead of function calls (like math.pow) and the more complex exponentiation operator (x^2), making it the fastest method in Garry's Mod's LuaJIT environment.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Do something with the player
end
```
Reason: `ipairs` is more efficient and semantically correct than `pairs` for iterating over sequentially indexed tables like the array returned by `player.GetAll()`.


CLI exited without a valid strict response.