```lua
for _, ent in ipairs( ents.FindByClass( "prop_physics" ) ) do
    -- Do something with ent
end
```
Reason: `ents.FindByClass` queries the engine directly to return a table containing only the requested entities, avoiding the massive memory overhead and iteration cost of using `ents.GetAll()` to build a table of every entity in the map.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Your code here
end
```
Reason: `ents.FindByClass` filters entities natively within the C++ engine and returns a table containing only the matching entities, bypassing the significant memory allocation and performance overhead of generating a Lua table of every single entity in the map via `ents.GetAll()`.


```lua
for _, ent in ipairs( ents.FindByClass( "prop_physics" ) ) do
    -- do something with ent
end
```
Reason: `ents.FindByClass` performs the class filtering on the C++ side and returns a table containing only the matching entities, avoiding the need to construct a massive table of all entities in the map (which `ents.GetAll()` does).


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Do something with ent
end
```
Reason: `ents.FindByClass("prop_physics")` directly returns a table containing only the entities that match the specified class, avoiding the performance and memory overhead of constructing a table of every single entity in the map like `ents.GetAll()` does.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- do something with ent
end
```
Reason: `ents.FindByClass` filters entities on the C++ side and returns a table containing only the matching entities, avoiding the costly memory allocation of building a table of all entities like `ents.GetAll()` does.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback logic goes here
end)
```
Reason: hook.Add is the standard Garry's Mod API function used to bind custom callbacks to engine events.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your think logic here
end)
```
Reason: `hook.Add` is the standard Garry's Mod function used to bind a callback to a specific game event hook using a unique string identifier.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- callback body
end)
```
Reason: hook.Add is the standard Garry's Mod function used to register a callback function to a specific event hook.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: The hook.Add function is the standard way to register callbacks to Garry's Mod events like Think.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: The `hook.Add` function is the standard API in Garry's Mod for attaching custom callbacks to specific engine events.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    -- Safe to call methods on ent
end
```
Reason: The `IsValid(ent)` global function safely checks that the variable is not nil and that the underlying engine entity has not been removed, preventing "Tried to use a NULL entity!" errors.


```lua
if IsValid(ent) then
    -- Safe to call methods on ent
end
```
Reason: The `IsValid()` global function safely checks that the variable is not nil, is an Entity object, and has not been removed from the game world (which would make it a NULL entity).


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


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: The global `IsValid(ent)` function ensures the variable is not nil and that its underlying C++ object has not been removed from the game world, preventing null pointer crashes.


```lua
if IsValid(ent) then
    -- It is safe to call methods on ent here
end
```
Reason: The global `IsValid()` function safely checks both that the Lua reference is not nil and that the underlying C++ game entity still exists and has not been removed.


```lua
net.Receive( "MyAddon.Sync", function( len, ply )
    -- Handle the incoming network message here
end )
```
Reason: net.Receive is the standard Garry's Mod function used to hook into and handle incoming net messages.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming network message here
end)
```
Reason: The net.Receive function registers a callback that listens for and handles incoming network messages matching the specified string identifier.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handler code goes here
end)
```
Reason: The net.Receive function is the standard Garry's Mod API for listening to incoming network messages by their registered string name.


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


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


```lua
local cachedAngle = Angle()

local function HotPath()
    -- Instead of local ang = Angle(), reuse the cached one:
    cachedAngle:Zero()

    -- Now you have a fresh, zeroed Angle to use without allocating memory
    -- (e.g., cachedAngle.p = 10, etc.)
end
```
Reason: Reusing a pre-allocated object and calling `:Zero()` avoids the overhead of object instantiation and subsequent garbage collection in a hot path.


```lua
local cachedAngle = Angle()

local function HotPath()
    cachedAngle:Zero()
    -- Modify and use cachedAngle here
end
```
Reason: Pre-allocating the Angle object once and resetting it with `:Zero()` avoids the performance overhead of continuous memory allocation and garbage collection in the hot path.


```lua
local cachedAngle = Angle()

local function HotPath()
    cachedAngle:Zero()
    -- Use cachedAngle without allocating a new object
end
```

Reason: Reusing a locally cached Angle object and resetting it with `:Zero()` avoids the memory allocation and garbage collection overhead of instantiating a new Angle object on every iteration.


```lua
local cachedAngle = Angle()

local function HotPath()
    cachedAngle:Zero()
    -- Use cachedAngle here
end
```
Reason: Mutating a cached object using :Zero() avoids the performance overhead of continuous memory allocation and garbage collection caused by creating new Angle() objects.


```lua
local temp_angle = Angle()

local function HotPathFunction()
    temp_angle:Zero()
    -- Use temp_angle for calculations here
end
```
Reason: Caching an Angle object outside the hot path and calling `:Zero()` on it reuses the existing object, avoiding the memory allocation and garbage collection overhead of creating a new `Angle()` every time.


```lua
local myaddon_config_color = Color(255, 255, 255)
surface.SetDrawColor(myaddon_config_color)
```
Reason: Local variables are accessed directly from fast registers by LuaJIT, bypassing the costly string hashing and memory lookups required for nested table indexing.


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

local function ApplyColor()
    surface.SetDrawColor(config_color)
end
```
Reason: Local variables are resolved at compile time to fast stack registers, completely avoiding the expensive hash dictionary lookups required by global variables or nested tables.


```lua
local config_color = Color(255, 255, 255)
local current_color = config_color
```
Reason: Local variables map directly to LuaJIT registers, avoiding the costly hash lookups and memory indirection required for nested table accesses.


```lua
local myaddon_config_color = Color(255, 255, 255)
local currentColor = myaddon_config_color
```
Reason: Local variables use fast register lookups in LuaJIT, whereas nested tables and globals require slower hash map lookups for every level of indexing.


```lua
local myaddon_config_color = Color(255, 255, 255)
local r = myaddon_config_color.r
```
Reason: Local variables are stored directly in Lua VM registers, avoiding the hash lookups and memory indirection required when traversing nested tables.


```lua
team.GetName(ply:Team())
```
Reason: In DarkRP, jobs are registered as standard Garry's Mod teams, making this the most efficient and reliable way to retrieve the job's display name without relying on less efficient networked strings.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: Jobs in DarkRP are built on top of the native Garry's Mod team system, which the Source engine already networks automatically and highly efficiently, completely avoiding the overhead of custom networked strings.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own custom networking system (DarkRPVars) to optimize bandwidth, making getDarkRPVar the correct and most efficient method to retrieve job information over standard GMod networked strings.


```lua
team.GetName(ply:Team())
```
Reason: DarkRP implements jobs using the native Garry's Mod team system, making this the standard and most efficient way to retrieve a job name without relying on less efficient network strings.


```lua
local jobName = team.GetName(ply:Team())
```
Reason: DarkRP implements jobs as Garry's Mod teams, making this the standard, most reliable, and performant method compared to querying arbitrary networked strings.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- Vectors are within the threshold distance
end
```
Reason: Using `DistToSqr` avoids the computationally expensive square root operation used by `Distance`, making it much faster for simple threshold comparisons.


```lua
vec1:DistToSqr(vec2) <= (threshold * threshold)
```
Reason: DistToSqr avoids the computationally expensive square root calculation used in standard distance checks, making it significantly faster for simple threshold comparisons.


```lua
if vec1:DistToSqr(vec2) < threshold ^ 2 then
    -- vectors are within the threshold distance
end
```
Reason: `DistToSqr` avoids the computationally expensive square root calculation required by exact distance checks, making it significantly more performant.


```lua
vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: DistToSqr avoids the expensive square root operation used in calculating the actual distance, making threshold comparisons much more performant.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- Vectors are within the threshold distance
end
```
Reason: `DistToSqr` avoids the computationally expensive square root operation used in standard distance calculations.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: `ents.Iterator()` avoids the performance cost and garbage collection overhead of creating a new sequential table, which happens when using `ents.GetAll()`.


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
end
```
Reason: ents.Iterator() is the wiki-recommended approach because it iterates sequentially without generating a new table, avoiding the memory allocation and garbage collection overhead of ents.GetAll().


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
end
```
Reason: ents.Iterator() is recommended over ents.GetAll() because it iterates without allocating a new table each time, significantly reducing garbage collection overhead and improving performance.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: ents.Iterator() is the modern, wiki-recommended approach as it is faster and avoids creating a new table allocation on every loop compared to ents.GetAll().


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: ents.Iterator() is the wiki-recommended approach because it provides a zero-allocation iterator, significantly improving performance and reducing garbage collection overhead compared to ents.GetAll().


Answer must contain 0 through 0 candidate loops.

```lua
local nearby_ents = ents.FindInSphere(ply:GetPos(), 512)
for i = 1, #nearby_ents do
    local ent = nearby_ents[i]
    if IsValid(ent) and ent ~= ply then
        -- process nearby entity
    end
end
```
Reason: ents.FindInSphere leverages the engine's underlying spatial partitioning (BSP/KD-tree) in C++ to instantly retrieve local entities, avoiding the severe performance cost of iterating and distance-checking every entity on the server.


```lua
local pos = ply:GetPos()
local offset = Vector(256, 256, 256)
local nearbyEnts = ents.FindInBox(pos - offset, pos + offset)
```
Reason: ents.FindInBox is consistently faster in GMod benchmarks than ents.FindInSphere because it relies on a simple AABB intersection check against the engine's spatial partition, completely skipping the mathematical overhead of calculating point-to-point distances for every entity in the leaf nodes.


```lua
local function GetEntitiesNearPlayer(ply, radius)
    return ents.FindInSphere(ply:GetPos(), radius)
end
```
Reason: ents.FindInSphere uses the Source engine's internal C++ spatial partition tree for rapid C-side culling, significantly outperforming manual distance checks against ents.GetAll() in Lua.


```lua
local nearby = ents.FindInSphere(ply:GetPos(), 256)
for i = 1, #nearby do
    local ent = nearby[i]
    if ent:IsValid() and ent ~= ply then
        -- Process entity here
    end
end
```
Reason: ents.FindInSphere utilizes the engine's internal spatial partitioning KD-tree to rapidly find entities within a radius, making it vastly more performant than iterating over all server entities.


```lua
local radius = 500
local nearbyEnts = ents.FindInSphere(ply:GetPos(), radius)
for i = 1, #nearbyEnts do
    local ent = nearbyEnts[i]
    if IsValid(ent) and ent ~= ply then
        -- Process entity
    end
end
```
Reason: ents.FindInSphere is executed natively in C++ using the engine's internal spatial partitioning, making it significantly faster than iterating through ents.GetAll() in Lua.


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

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

    return found
end
```
Reason: Iterating over the small, cached list of players via player.GetAll() and using DistToSqr avoids searching through thousands of map entities in the spatial partition and skips computationally expensive square root calculations.


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

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

    return playersInRadius
end
```
Reason: Iterating `player.GetAll()` and checking squared distances is much faster because it only evaluates players (a maximum of 128) rather than searching through every entity in the map's spatial partition and creating a large intermediate table.


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

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

    return playersInRadius
end
```
Reason: Iterating the small, cached list from player.GetAll() and performing a simple squared distance check in Lua avoids querying the engine's spatial partition and filtering through numerous non-player entities.


```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 player.GetAll() and checking DistToSqr is much faster because it only loops through a maximum of 128 players using fast squared distance math, avoiding the heavy overhead of ents.FindInSphere checking the spatial partition for potentially thousands of props and non-player entities.


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

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

    return players
end
```
Reason: Iterating over the much smaller player.GetAll() table using DistToSqr avoids the massive overhead of ents.FindInSphere querying the spatial partition and checking thousands of non-player entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric for loop uses specialized, highly optimized bytecode instructions that manage the loop counter and condition internally, avoiding the overhead of explicit variable updates and condition checks required by a while loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops use specialized internal bytecode instructions to manage the counter and condition, avoiding the explicit variable increment and comparison overhead of a while loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric for loop is generally faster in Lua/LuaJIT because it uses specialized, optimized VM instructions for the iteration step, whereas a while loop requires separate instructions for incrementing and condition checking.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric `for` loops are natively optimized by LuaJIT with internal control variables, making them faster than manually incrementing and evaluating conditions in a `while` loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: LuaJIT has specialized bytecode instructions for numeric for loops and optimizes them far more aggressively than while loops, which require explicit condition checking and variable incrementing.


```lua
local function Tick()
    local plys = player.GetAll()

    -- Faster pattern: Call the hook once and pass the players
    hook.Run("TickPlayers", plys)

    -- Slower pattern (avoid): Calling the hook per player
    -- for i = 1, #plys do
    --     hook.Run("TickPlayer", plys[i])
    -- end
end

hook.Add("TickPlayers", "CustomLogic", function(plys)
    for i = 1, #plys do
        local ply = plys[i]
        -- execute logic for ply
    end
end)
```

Reason: Calling `hook.Run` has inherent overhead from internal table lookups and function dispatching; doing this once per tick instead of once per player drastically reduces this overhead.


```lua
hook.Add("Tick", "BroadcastTickToPlayers", function()
    local plys = player.GetAll()
    hook.Run("CustomPlayerLogic", plys)
end)

hook.Add("CustomPlayerLogic", "ProcessPlayerLogic", function(plys)
    for i = 1, #plys do
        local ply = plys[i]
        -- Execute custom logic for each player here
    end
end)
```
Reason: Calling `hook.Run` has inherent overhead, so executing it just once per tick and looping through the players inside the listener is significantly faster than triggering the hook for every single player individually.


```lua
hook.Add("Tick", "NotifyAllPlayers", function()
    local plys = player.GetAll()
    hook.Run("CustomPlayerLogicTick", plys)
end)
```
Reason: Calling hook.Run incurs overhead from looking up and iterating the internal hooks table, so calling it once per tick instead of once per player drastically reduces this overhead.


```lua
hook.Add("Tick", "BroadcastCustomLogic", function()
    hook.Run("CustomPlayerTick", player.GetAll())
end)
```
Reason: Calling hook.Run once per tick avoids the repetitive internal overhead of hook table lookups and function dispatch that would otherwise occur for every single player.


```lua
hook.Add("Tick", "NotifyPlayers", function()
    local plys = player.GetAll()
    hook.Run("CustomLogicAllPlayers", plys)
end)
```
Reason: `hook.Run` incurs internal overhead from string hashing and iterating over registered listeners, so calling it once per tick is significantly faster than executing it repeatedly inside a player loop.


```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 executing multiple function calls and C++ boundary crossings every frame.


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

    local hp = ply:Health()

    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 10, color_white)
    surface.DrawRect(10, 30, hp * 2, 20)
    draw.RoundedBox(4, 10, 60, hp * 2, 20, color_white)
end)
```
Reason: Caching the result of LocalPlayer():Health() in a local variable avoids multiple expensive C++ boundary function calls during a single render frame.


```lua
hook.Add("HUDPaint", "OptimizedHUDDraw", 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.RoundedBox(0, 50, 70, hp, 20, color_white)
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(50, 100, hp, 20)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids the overhead of traversing the C++ boundary multiple times per frame for the same unchanging value.


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

    local health = ply:Health()

    draw.SimpleText("HP: " .. health, "DermaDefault", 50, 50, color_white)
    draw.SimpleText("HP: " .. health, "DermaDefault", 50, 70, color_white)
    draw.SimpleText("HP: " .. health, "DermaDefault", 50, 90, color_white)
end)
```
Reason: Caching the result of `LocalPlayer():Health()` in a local variable avoids the overhead of executing multiple function calls and crossing the Lua/C++ boundary repeatedly within the same frame.


```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", 10, 10, color_white)
    draw.SimpleText("Health (Shadow): " .. hp, "DermaDefault", 11, 11, color_black)
    surface.DrawRect(10, 30, hp, 15)
end)
```
Reason: Caching the result in a local variable eliminates the performance overhead of making redundant Lua-to-C++ API calls for `LocalPlayer()` and `Health()` during every frame.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cachedColor)
    surface.DrawRect(10, 10, 100, 100)
end)
```
Reason: Caching the Color object outside the hook prevents a new table from being allocated every frame, significantly reducing garbage collection overhead and improving performance.


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

hook.Add("HUDPaint", "OptimizedPaint", function()
    -- Use the locally cached color or the built-in GMod global 'color_white'
    surface.SetDrawColor(myColor)
end)
```
Reason: Caching the color object outside the render hook prevents expensive function calls and memory allocations on every single frame.


```lua
local myColor = Color(255, 255, 255)
hook.Add("HUDPaint", "MyPaintHook", function()
    surface.SetDrawColor(myColor)
    -- Or you can simply use the built-in color_white global
    -- surface.SetDrawColor(color_white)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Caching the Color object outside the hook or using the built-in `color_white` global prevents unnecessary memory allocations every frame, which avoids triggering the garbage collector frequently and causing frame drops.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cachedColor)
    -- Alternatively, for pure white, use the built-in global: surface.SetDrawColor(color_white)
end)
```
Reason: Caching the Color object outside the loop prevents a new table from being allocated every frame, significantly reducing memory generation and garbage collection lag.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(my_color)
    -- Paint operations go here
end)
```
Reason: Caching the Color object outside the render hook prevents creating a new table every frame, which significantly reduces garbage collection overhead and improves performance.


```lua
local sin = math.sin
for i = 1, 10000 do
    local result = sin(i)
end
```
Reason: Caching the function in a local variable avoids repeated hash table lookups in the global environment, which is significantly faster in Lua.


```lua
local sin = math.sin
for i = 1, 10000 do
    local val = sin(i)
end
```
Reason: Local variable lookups in Lua use fast register access, which is significantly faster than performing expensive global table lookups for `math.sin` on every iteration of a hot loop.


```lua
local sin = math.sin
for i = 1, 10000 do
    local val = sin(i)
end
```
Reason: Local variables in Lua are stored in registers, making them significantly faster to access than global table lookups like math.sin.


```lua
local sin = math.sin
for i = 1, 100000 do
    local val = sin(i)
end
```
Reason: Caching a global function to a local variable avoids repeated expensive global table lookups during each loop iteration.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local val = sin(i)
end
```
Reason: Local variables in Lua are accessed much faster than global table lookups because they are mapped directly to registers, bypassing the hash table lookup for `math` and `sin` on every iteration.


```lua
local ply

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

    -- Use the cached 'ply' here instead of calling LocalPlayer()
end)
```
Reason: Caching the player entity in a local variable and only calling LocalPlayer() when the cache is invalid avoids the performance overhead of repeated C++ function calls in high-frequency hooks.


```lua
local ply = NULL

hook.Add("InitPostEntity", "CacheLocalPlayer", function()
    ply = LocalPlayer()
end)
```
Reason: Caching the player entity once it initializes avoids both the global table lookup and the expensive C++ boundary call required by LocalPlayer() in high-frequency hooks.


```lua
local ply = NULL

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

    -- ply is now valid and cached, use it safely here
    -- print(ply:Nick())
end)
```
Reason: Caching the entity object in an upvalue avoids the continuous overhead of the global function call and the C-side entity lookup every single frame.


```lua
local LocalPlayer = LocalPlayer
```
Reason: Localizing the global function caches its reference in a local register, avoiding a slower global table lookup in `_G` each time it is called.


```lua
local LocalPlayer = LocalPlayer
```
Reason: Local variable lookups in Lua are significantly faster than global environment lookups.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    -- Check if both players' aim vectors align with the direction toward each other
    return ply1:GetAimVector():Dot(dir) > (threshold or 0.8) and ply2:GetAimVector():Dot(-dir) > (threshold or 0.8)
end
```
Reason: The dot product of two normalized vectors directly yields the cosine of the angle between them, allowing you to compare the result against a simple threshold rather than performing expensive trigonometric inverse functions like `math.acos`.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(-dir) > threshold
end
```
Reason: Dot products directly return the cosine of the angle between two normalized vectors, allowing you to use a simple scalar comparison (e.g., > 0.8) instead of the expensive math.acos function.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    -- threshold defaults to -0.8 (approx 143 to 180 degrees opposing)
    threshold = threshold or -0.8
    return ply1:GetAimVector():Dot(ply2:GetAimVector()) < threshold
end
```
Reason: The dot product of two normalized vectors directly yields the cosine of the angle between them (approaching -1 as they face opposite directions), allowing a simple threshold check without expensive trigonometric functions.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8 -- 0.8 represents roughly a 36-degree cone

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

    local ply1Looking = ply1:GetAimVector():Dot(dir) > threshold
    local ply2Looking = ply2:GetAimVector():Dot(-dir) > threshold

    return ply1Looking and ply2Looking
end
```
Reason: The dot product of two normalized vectors directly yields the cosine of the angle between them, which allows you to compare angles using simple arithmetic instead of relying on expensive trigonometric functions like math.acos.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, dotTolerance)
    dotTolerance = dotTolerance or 0.8
    local dir = (ply2:EyePos() - ply1:EyePos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > dotTolerance and ply2:GetAimVector():Dot(-dir) > dotTolerance
end
```
Reason: The dot product operation directly returns the cosine of the angle between two normalized vectors, allowing you to use a simple and fast scalar comparison instead of an expensive trigonometric math.acos call.


```lua
SomeHelper(ply)
```
Reason: Metatable lookups for methods incur overhead in Lua compared to direct function calls (especially if the function is localized).


```lua
SomeHelper(ply)
```
Reason: Calling ply:SomeHelper() requires an additional metatable index lookup to resolve the function, making a direct function call faster.


```lua
SomeHelper(ply)
```
Reason: SomeHelper(ply) avoids the expensive userdata metatable lookup required by ply:SomeHelper().


```lua
SomeHelper(ply)
```
Reason: It avoids the overhead of the metatable __index lookup required by ply:SomeHelper().


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the overhead of metatable lookups required by object-oriented method syntax.


```lua
MsgN("Debug information")
```
Reason: MsgN directly calls the engine's console output function, bypassing the overhead of Garry's Mod's overridden `print` function which does additional formatting and argument processing.


```lua
MsgN("debug line")
```
Reason: MsgN is a direct engine function that bypasses the variadic formatting overhead and hook calls associated with the global print function.


```lua
MsgN("debug message")
```
Reason: MsgN is a direct C binding to the engine console that bypasses the formatting and argument processing overhead of the global print function.


```lua
MsgN("Debug line")
```
Reason: MsgN is a direct engine C++ binding that bypasses the Lua-side formatting and overhead of the standard print function.


```lua
MsgN("debug line")
```
Reason: `MsgN` is faster than `print` because it directly interfaces with the engine console output without the additional Lua-side formatting and vararg processing overhead.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: A numeric for loop is the fastest because it avoids the function call overhead associated with the iterator functions used by pairs and ipairs, which is especially beneficial in GMod's LuaJIT environment.


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


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: A numeric for loop avoids the function call overhead of iterator functions like pairs or ipairs, allowing LuaJIT to optimize and execute it the fastest.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: A numeric for loop avoids the function call overhead of iterators like pairs or ipairs and is optimally traced and compiled by LuaJIT.


```lua
for i = 1, #myTable do
    local value = myTable[i]
    -- do something with value
end
```
Reason: Numeric for loops are the fastest in Garry's Mod (which uses LuaJIT) because they avoid the overhead of calling iterator functions like those used in pairs and ipairs, allowing the JIT compiler to highly optimize the sequential array access.


```lua
local result = {}
local index = 1
for i = 1, #inputList do
    local item = inputList[i]
    if item.isValid then
        result[index] = item.name
        index = index + 1
    end
end
```
Reason: A single-pass imperative loop avoids function call overhead and intermediate table allocations, allowing LuaJIT to trace and optimize it far more efficiently than the nested closures of the `fn` library.


```lua
local result = {}
local index = 1
for i = 1, #inputList do
    local item = inputList[i]
    if item:IsValid() then -- Filter condition
        result[index] = item:GetName() -- Map transform
        index = index + 1
    end
end
```
Reason: A single imperative loop with manual table indexing avoids the heavy garbage collection overhead of intermediate table allocations and closure calls inherent to functional libraries like `fn`.


```lua
local result = {}
local n = 0
for i = 1, #inputList do
    local item = inputList[i]
    if item.active then
        n = n + 1
        result[n] = item.price * 2
    end
end
```
Reason: Manual iterative loops with a local counter avoid the function call overhead, closure allocations, and intermediate table creations that occur when chaining DarkRP's `fn.Filter` and `fn.Map`.


```lua
local function filterMapEvens(list)
    local result = {}
    local index = 1
    for i = 1, #list do
        local val = list[i]
        -- filter condition integrated with the map transformation
        if val % 2 == 0 then
            result[index] = val * val
            index = index + 1
        end
    end
    return result
end
```
Reason: A single imperative loop avoids the multiple intermediate table allocations and function call overheads inherent in functional combinator chains, allowing LuaJIT to fully trace and optimize the execution.


```lua
local function filterMapItems(items)
    local result = {}
    local index = 1
    for i = 1, #items do
        local item = items[i]
        if item.score > 10 then
            result[index] = item.name
            index = index + 1
        end
    end
    return result
end
```
Reason: Imperative loops avoid the overhead of function calls, closure allocations, and intermediate table creations present in DarkRP's fn library, allowing LuaJIT to compile and optimize the operations effectively.


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

hook.Add("PlayerInitialSpawn", "Cache_PlayerJoin", function(ply)
    table.insert(active_players, ply)
end)

hook.Add("PlayerDisconnected", "Cache_PlayerLeave", function(ply)
    table.RemoveByValue(active_players, ply)
end)

hook.Add("Think", "Optimized_PlayerThink", function()
    for i = 1, #active_players do
        local ply = active_players[i]
        -- Fast per-player tick logic here
    end
end)
```
Reason: Calling player.GetAll() allocates a new table and triggers garbage collection overhead on every tick, whereas maintaining a persistent array avoids allocation entirely and allows for faster numerical iteration.


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

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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCache_Join", UpdatePlayerCache)

hook.Add("PlayerDisconnected", "UpdatePlayerCache_Leave", function()
    -- timer.Simple(0) waits for the next frame so the disconnecting player is fully removed from player.GetAll()
    timer.Simple(0, UpdatePlayerCache)
end)

hook.Add("Think", "OptimizedPlayerThink", function()
    -- A numeric loop is slightly faster than ipairs in LuaJIT and avoids iterator overhead
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Per-player logic here
        end
    end
end)
```
Reason: Calling player.GetAll() every tick allocates a new table and crosses the C++/Lua boundary, generating garbage and wasting CPU; caching the results and updating only on connect/disconnect events bypasses this overhead entirely.


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

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

hook.Add("EntityRemoved", "UpdatePlayerCache_Leave", function(ent)
    if ent:IsPlayer() then
        table.RemoveByValue(cachedPlayers, ent)
    end
end)

hook.Add("Tick", "OptimizedTick", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        -- Perform tick logic with ply here
    end
end)
```
Reason: Calling `player.GetAll()` every tick generates a new table, causing significant garbage collection overhead; caching the table and updating it only on entity spawn/removal eliminates this allocation while allowing for faster numeric `for` loop iteration.


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

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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCacheJoin", UpdatePlayerCache)
hook.Add("PlayerDisconnected", "UpdatePlayerCacheLeave", function()
    timer.Simple(0, UpdatePlayerCache)
end)

hook.Add("Tick", "OptimizedTick", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Your per-tick player logic here
        end
    end
end)
```
Reason: Calling player.GetAll() allocates a new table every tick which causes heavy garbage collection overhead, whereas caching it and iterating with a numeric for-loop eliminates table creation entirely during the tick.


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

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

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

hook.Add("Think", "OptimizedPlayerLoop", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Perform per-tick logic here
        end
    end
end)
```
Reason: Caching the table and using a numeric for-loop avoids allocating a new table and iterator function every tick, significantly reducing garbage collection overhead and CPU usage.


```lua
local playerData = {}

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

-- Reading data
local myData = playerData[ply]
```
Reason: Indexing a plain Lua table is significantly faster than indexing a userdata object (the player entity), which requires a relatively expensive metatable `__index` lookup to cross the C boundary.


```lua
local player_data = {}

-- Fast write
player_data[ply] = "value"

-- Fast read
local value = player_data[ply]
```
Reason: Indexing a standard Lua table avoids the slow C++ userdata metatable __index lookups associated with reading custom fields directly from the player object.


```lua
local playerData = {}

-- Writing
playerData[ply] = value

-- Reading
local value = playerData[ply]
```
Reason: Using a standard Lua table avoids the slow C++ metatable `__index` lookups that occur when accessing custom fields directly on Entity userdata objects.


```lua
local playerData = {}

-- Writing data
playerData[ply] = someValue

-- Reading data (much faster)
local myData = playerData[ply]
```
Reason: Storing data in a local Lua table bypasses the expensive C/C++ metamethod lookups (__index) associated with the Player userdata object.


```lua
local temporaryPlayerData = {}

-- Writing
temporaryPlayerData[ply] = value

-- Reading
local val = temporaryPlayerData[ply]
```
Reason: Indexing a standard Lua table avoids the overhead of traversing the `__index` and `__newindex` metamethods bridging to C++ that occur when reading or writing fields directly on the Entity userdata object.


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

for i = 1, #myTable do
    local val = myTable[i]
    -- do something with val
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for loop are significantly faster in LuaJIT because they access the array part of the table directly, avoiding the overhead of hash map lookups and iterator function calls associated with `pairs()`.


```lua
local my_collection = {
    "value1",
    "value2",
    "value3",
    "value4"
}

for i = 1, #my_collection do
    local v = my_collection[i]
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for loop avoid the function call overhead of pairs() and the hashing cost of string lookups, which is highly optimized in Garry's Mod's LuaJIT environment.


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

for i = 1, #sequentialArray do
    local value = sequentialArray[i]
    print(value)
end
```
Reason: Sequential number-indexed arrays are faster because they utilize the contiguous array part of Lua's table structure and can be traversed with a highly optimized numeric for loop, avoiding the overhead of hash table lookups required by string-keyed maps.


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

for i = 1, #fast_array do
    local value = fast_array[i]
    -- Process value
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for-loop avoid hash map lookups and benefit significantly more from LuaJIT optimizations than string-keyed maps using pairs().


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

for i = 1, #fastTable do
    local value = fastTable[i]
end
```
Reason: Sequential number-indexed arrays can be iterated using a numerical for loop (or `ipairs`), which avoids the overhead of hash map lookups and iterator function calls required by `pairs` on string-keyed maps, making it significantly faster in LuaJIT (Garry's Mod).


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numbers is faster because it avoids the overhead of table field lookups in the C++ binding.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate numeric arguments avoids the overhead of Lua table creation, garbage collection, and field lookups associated with passing a Color object.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing primitive numbers directly to the C/C++ boundary is faster in LuaJIT as it avoids table metatable lookups, object allocation, and garbage collection overhead.


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


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing primitive numbers directly avoids table lookups, object allocation, and the internal C++ extraction costs associated with passing a Color table.


```lua
local result = sql.Query("SELECT * FROM players WHERE steamid = 'STEAM_0:0:123456'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite operates directly on the server's filesystem and executes synchronously without network round-trip overhead.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345678'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite has lower latency than remote MySQL because it eliminates network round-trip overhead and performs operations directly on the local filesystem.


```lua
local data = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:1234567'")
```
Reason: Local SQLite avoids network round-trip latency by executing queries directly on the server's local file system.


```lua
local result = sql.Query("SELECT * FROM player_stats WHERE steamid = 'STEAM_0:1:12345678' LIMIT 1")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite reads and writes directly to a local file (sv.db), completely eliminating the network round-trip latency required by remote MySQL queries.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345678'")
if result then
    -- Process the data
end
```
Reason: Local SQLite operates directly on local storage without any network round-trip overhead, resulting in fundamentally lower latency for a single isolated server than querying 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: Caching the SteamID string directly on the player entity table avoids the overhead of repeated C++ boundary crossings and new string allocations.


```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 field lookups are significantly faster than repeatedly crossing the Lua-C++ boundary to invoke engine methods.


```lua
local steamIDCache = {}

hook.Add("PlayerInitialSpawn", "CacheSteamIDs", function(ply)
    steamIDCache[ply] = ply:SteamID()
end)

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

-- Hot path usage:
-- local id = steamIDCache[ply]
```
Reason: Indexing a local Lua table by the player object entirely bypasses the expensive C++ userdata __index metamethod overhead and function call cost of ply:SteamID().


```lua
hook.Add("PlayerAuthed", "CachePlayerSteamID", function(ply, steamid)
    ply.CachedSteamID = steamid
end)

local function HotPathExample(ply)
    -- Fast Lua table lookup, falling back to the method if called too early
    local steamID = ply.CachedSteamID or ply:SteamID()
    -- ...
end
```
Reason: Accessing a value directly from the Lua entity table avoids the expensive Lua-to-C++ boundary crossing overhead incurred when calling engine methods like ply:SteamID().


```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: Table indexing avoids the overhead of a C++ function call and string allocation inherent in repeatedly calling ply:SteamID().


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "piece_" .. i
end
local final_string = table.concat(pieces)
```
Reason: table.concat allocates memory once for the final string, avoiding the quadratic memory reallocation overhead of creating intermediate strings with repeated `..` operators.


```lua
local parts = {}
for i = 1, 10000 do
    parts[#parts + 1] = "piece"
end
local finalString = table.concat(parts)
```
Reason: table.concat allocates memory once for the final string instead of creating thousands of intermediate string objects, avoiding quadratic memory reallocation overhead.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "piece_" .. i
end
local large_string = table.concat(pieces)
```
Reason: Using table.concat is faster because it allocates memory for the final string all at once, avoiding the heavy quadratic performance cost and garbage collection overhead of constantly creating intermediate string objects with the .. operator.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "small_piece_" .. i
end
local finalString = table.concat(pieces)
```
Reason: table.concat avoids the overhead of repeatedly allocating memory and garbage collecting intermediate string objects during each concatenation step.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "small_piece_" .. i
end
local large_string = table.concat(pieces, "")
```
Reason: Using table.concat joins all elements in a single C-level pass, avoiding the O(n^2) performance cost and heavy garbage collection overhead caused by repeatedly allocating new intermediate strings with the .. operator.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Calling the `surface` library functions directly avoids the overhead of the `draw.RoundedBox` function call and its internal conditional checks.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: Using the surface library directly avoids the Lua function call overhead and conditional checks performed inside draw.RoundedBox.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Calling surface.SetDrawColor and surface.DrawRect directly skips the Lua function overhead, table lookups, and corner radius conditional checks internally performed by draw.RoundedBox.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Using the surface library directly is a C++ binding that bypasses the additional Lua function call overhead and radius checks performed internally by draw.RoundedBox.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: Calling the underlying surface library functions directly avoids the overhead of draw.RoundedBox's internal conditional checks for corner radius and color unpacking.


```lua
hook.Add("HUDPaint", "FastTextDrawing", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText("This is the fastest approach")
end)
```
Reason: Calling the native `surface.*` functions directly acts as a direct C++ binding, bypassing the Lua overhead, table lookups, and text alignment math that the `draw.*` wrapper library performs internally on every frame.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(50, 50)
surface.DrawText("Fast single-line string")
```
Reason: `surface.DrawText` and its setup functions are direct C-bindings that bypass the additional alignment math, table lookups, and function call overhead inherent in the `draw.*` Lua wrappers.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Single line text")
```
Reason: Using the `surface.*` functions directly avoids the Lua-side overhead and alignment calculations present in the `draw.*` wrapper library.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Hello World")
```
Reason: The surface library functions are the lowest-level text rendering bindings available in Lua; wrapper functions like draw.SimpleText add unnecessary overhead for single lines.


```lua
surface.SetFont("Default")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Hello World")
```
Reason: Calling the surface.* C-bindings directly is faster because it avoids the internal Lua wrapper overhead and table lookups present in the draw.* library functions.


```lua
#table_name
```
Reason: The `#` length operator is the standard and most performant way to get the length of a sequential array-like table in Lua 5.1.


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


```lua
local length = #myTable
```
Reason: The `#` length operator is the standard, most performant way in Lua 5.1/Garry's Mod to get the size of a sequential, 1-indexed array-like table without gaps.


```lua
#table
```
Reason: The `#` operator is the native, most efficient, and idiomatic way to get the length of a sequential table in Lua.


```lua
local length = #myTable
```
Reason: The `#` operator is built into standard Lua, executes faster than function calls like `table.Count`, and is the idiomatic way to get the length of a sequential array-like table.


```lua
t = {}
```
Reason: Assigning a new empty table is an O(1) operation that executes much faster than `table.Empty(t)`, which must perform an O(n) iteration over every element to clear them, even though replacing the table does increase garbage collection overhead.


```lua
t = {}
```
Reason: Creating a new table is O(1) and leaves the old table to the garbage collector, whereas table.Empty(t) is O(n) because it iterates through all elements to set them to nil.


```lua
t = {}
```
Reason: Reassigning the variable to an empty table is O(1) and generally faster than table.Empty() which iterates through every element in O(N) time.


```lua
t = {}
```
Reason: Reassigning to a new table is an O(1) operation that avoids the O(n) overhead of table.Empty() iterating through every key to set it to nil.


```lua
t = {}
```
Reason: Creating a new table is an O(1) allocation that avoids the O(n) iteration overhead of table.Empty() clearing each key individually.


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

-- Checking for existence
if mySet["banana"] then
    -- Do something
end
```
Reason: Key-based lookups use a hash map providing O(1) time complexity, whereas `table.HasValue` iterates over every element sequentially with O(n) time complexity.


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

-- Check existence
if mySet["apple"] then
    -- Value exists
end
```
Reason: Key lookups in Lua tables perform an O(1) hash map access, whereas table.HasValue runs an O(n) sequential loop.


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

if mySet["apple"] then
    print("Exists!")
end
```
Reason: Key lookups in Lua tables are O(1) time complexity, whereas table.HasValue sequentially iterates through the table in O(n) time.


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

-- Fast check using the value as the key
if lookupTable["banana"] then
    print("Value exists!")
end
```
Reason: Indexing a table key is an O(1) hash map lookup, which is significantly faster than the O(n) sequential linear search used by table.HasValue.


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

-- Check if value exists
if mySet["apple"] then
    print("Value exists!")
end
```
Reason: Using table keys for lookups provides O(1) time complexity (hash map lookup), which is significantly faster than the O(n) sequential search performed by `table.HasValue`.


```lua
local t = {a = 1, b = 2, c = 3}
```
Reason: Defining fields in the table constructor allows Lua to pre-allocate the exact size for the array and hash parts, avoiding costly memory reallocations that occur when adding fields sequentially.


```lua
local myTable = {
    x = 1,
    y = 2,
    z = 3
}
```
Reason: Defining fields inside the table constructor allows Lua to pre-allocate the exact number of required slots, avoiding memory reallocation and rehashing overhead that occurs when inserting into an empty table.


```lua
local t = { a = 1, b = 2 }
```
Reason: Defining fields within the constructor allows Lua to pre-allocate the table with the correct size instantly, avoiding multiple expensive memory reallocations and rehashes that occur when inserting fields one by one.


```lua
local t = {field1 = 1, field2 = 2, field3 = 3}
```
Reason: Using the table constructor pre-allocates the exact memory size needed for the fields, preventing expensive table rehashing and reallocation operations that occur when adding fields one by one to an initially empty table.


```lua
local tbl = { a = 1, b = 2, c = 3 }
```
Reason: Defining fields directly in the table constructor allows LuaJIT to pre-allocate the correct table size in memory, avoiding multiple assignment operations and costly table re-hashing.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Using math.random(#tbl) directly accesses the index in O(1) time, avoiding the expensive O(N) pairs() iteration that table.Random uses to support non-sequential keys.


```lua
local random_element = tbl[math.random(#tbl)]
```
Reason: table.Random iterates over the table using pairs making it O(n), whereas using the length operator (#) and direct indexing is O(1) for sequential tables.


```lua
local function GetRandomSequential(tbl)
    return tbl[math.random(1, #tbl)]
end
```
Reason: Using the length operator `#` and `math.random` allows O(1) direct access by index, bypassing the slow `pairs` iteration that `table.Random` must use to support non-sequential dictionaries.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: math.random(#tbl) accesses the index in O(1) time, bypassing table.Random's O(N) overhead of counting elements and iterating with pairs.


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


```lua
local squared = x * x
```
Reason: Multiplication (`x * x`) avoids the function call overhead of `math.pow` and the generic exponentiation logic of the `^` operator, making it significantly faster in LuaJIT.


```lua
local result = x * x
```
Reason: Multiplication `x * x` is significantly faster than `x ^ 2` or `math.pow` because it avoids the overhead of function calls and complex exponentiation logic, which is critical in LuaJIT tight loops.


```lua
local squared = x * x
```
Reason: Simple multiplication `x * x` avoids the overhead of function calls or exponentiation operators, compiling directly to a fast multiply instruction in LuaJIT.


```lua
local squared = x * x
```
Reason: In LuaJIT (used by Garry's Mod), direct multiplication is evaluated faster than the exponentiation operator (`x ^ 2`) or a function call (`math.pow(x, 2)`).


```lua
local result = x * x
```
Reason: Direct multiplication is significantly faster than using the exponentiation operator (`x ^ 2`) or `math.pow` because it maps directly to a simple CPU multiplication instruction, bypassing function call and complex math evaluation overhead in LuaJIT.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
```
Reason: `player.GetAll()` returns a sequentially indexed table, making `ipairs` the correct and more performant choice over `pairs` in LuaJIT.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
```
Reason: `player.GetAll()` returns a sequentially indexed table, so using `ipairs` is faster and more idiomatic than `pairs`.


```lua
for _, ply in ipairs( player.GetAll() ) do
    -- Your code here
end
```
Reason: ipairs is faster than pairs for iterating over sequential tables like the one returned by player.GetAll().


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
```
Reason: `ipairs` is faster and preferred over `pairs` for iterating over sequential, numerically-indexed tables like the one returned by `player.GetAll()`.


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


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Your code here
end
```
Reason: `ents.FindByClass` queries the engine directly to create and return a table containing only the entities of the requested class, completely avoiding the memory allocation and performance overhead of `ents.GetAll()` which builds a table of every single entity in the map.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- do something with ent
end
```
Reason: ents.FindByClass filters entities on the C++ side and only returns a Lua table containing the matching entities, avoiding the overhead of creating a table of all entities like ents.GetAll() would.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Your code here
end
```
Reason: `ents.FindByClass("prop_physics")` offloads the filtering to the C++ engine to build and return a small table of only the matching entities, completely avoiding the massive memory allocation and performance overhead of generating a table of every single entity in the map like `ents.GetAll()` does.


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


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Do something with ent
    end
end
```
Reason: `ents.Iterator()` provides a stateless iterator to traverse all entities without allocating a table in memory, avoiding the performance and memory overhead of `ents.GetAll()`.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- code here runs every tick
end)
```
Reason: The `hook.Add` function is the standard API in Garry's Mod for registering callbacks to engine events like "Think" with a unique identifier.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Code to run every tick goes here
end)
```
Reason: The `hook.Add` function is the standard way to register event callbacks in Garry's Mod, requiring the event name ("Think"), a unique identifier ("MyAddon.Think") to manage the hook, and the callback function to execute.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: hook.Add is the standard Garry's Mod function used to attach a callback to an engine hook.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: `hook.Add` is the standard Garry's Mod function for attaching callbacks to specific engine events.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your code here
end)
```
Reason: This uses the standard Garry's Mod `hook.Add` function to attach a callback function to the "Think" event under the unique identifier "MyAddon.Think".


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: The global IsValid function safely checks that the variable is not nil and that the underlying game entity has not been deleted.


```lua
if IsValid(ent) then
    -- safe to use ent
end
```
Reason: `IsValid(ent)` checks both if the variable is non-nil and if the underlying engine entity it refers to has not been removed or destroyed.


```lua
if IsValid(ent) then
    -- It is safe to call methods on ent
end
```
Reason: The global `IsValid(ent)` function safely checks that the variable is not nil and that the underlying C++ entity still exists in the game world and has not been removed.


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: The global IsValid() function safely checks if the variable is not nil and ensures the underlying C++ entity has not been removed from the game.


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


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


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


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


```lua
net.Receive( "MyAddon.Sync", function( len, ply )
    -- Handler code goes here
end )
```
Reason: `net.Receive` is the Garry's Mod function used to execute a callback when a specific network message is received.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message here
end)
```
Reason: `net.Receive` is the standard Garry's Mod API function used to listen for and handle incoming network messages by their string identifier.


```lua
local cached_angle = Angle()

local function HotPath()
    cached_angle:Zero()
    -- Use cached_angle
end
```
Reason: Reusing a localized Angle object and resetting it with :Zero() avoids continuous memory allocations and the resulting garbage collection overhead.


```lua
local tempAngle = Angle()

local function HotPath()
    tempAngle:Zero()
    -- Use tempAngle here
end
```
Reason: Pre-allocating an Angle object outside the hot path and resetting it with :Zero() avoids repeated memory allocation and prevents garbage collection spikes.


```lua
local temp_angle = Angle()

local function HotPath()
    temp_angle:Zero()
    -- use temp_angle here
end
```
Reason: Reusing a single pre-allocated Angle and resetting it avoids continuous memory allocation and reduces garbage collection overhead.


```lua
local temp_angle = Angle()

local function MyHotPath()
    temp_angle:Zero()
    -- Use temp_angle here instead of creating a new Angle()
end
```
Reason: Reusing a cached local variable and resetting it with `:Zero()` avoids the performance cost of continuous memory allocation and garbage collection overhead.


```lua
local cachedAngle = Angle()

local function HotPath()
    cachedAngle:Zero()
    -- Use cachedAngle for your calculations instead of creating a new Angle()
end
```
Reason: Reusing a pre-allocated Angle object and resetting it with :Zero() prevents continuous memory allocations and subsequent garbage collection overhead.


```lua
local myaddon_config_color = Color(255, 255, 255)
local current_color = myaddon_config_color
```
Reason: Local variables use fast, direct register indexing in LuaJIT, completely avoiding the expensive string hashing and multiple dictionary lookups required to access nested table fields.


```lua
local myaddon_config_color = Color(255, 255, 255)
local r = myaddon_config_color.r
```
Reason: Local variables use register-based access, completely bypassing the expensive string hashing and dictionary lookups required when indexing into nested global tables.


```lua
local myaddon_config_color = Color(255, 255, 255)
local current_color = myaddon_config_color
```
Reason: Local variables are mapped directly to registers in LuaJIT, making them significantly faster than nested tables which require multiple hash map lookups for each access.


```lua
local myaddon_config_color = Color(255, 255, 255)
local current_color = myaddon_config_color
```
Reason: Local variables in Lua(JIT) are accessed directly by register index, avoiding the expensive hash lookups required for every level of a nested table.


```lua
local myaddon_config_color = Color(255, 255, 255)
local current_color = myaddon_config_color
```
Reason: Local variables are stored directly in VM registers in LuaJIT, bypassing the expensive hash lookups required when indexing into nested tables or global variables.


```lua
team.GetName(ply:Team())
```
Reason: DarkRP jobs are implemented using Garry's Mod's native team system, making this the most efficient and standard way to retrieve a player's job name without unnecessary networking overhead.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system and `getDarkRPVar` is the official API to access these variables, ensuring forward compatibility and correctly handling custom job titles.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system (DarkRPVars) which is more bandwidth-efficient than default NWStrings and properly handles custom player-set job titles.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized custom networking system for player variables, making `getDarkRPVar` the required and reliable method to retrieve synchronized data like the job name string.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system to save bandwidth, bypass Garry's Mod's native NWString limits, and properly return custom job titles (like those set via `/job`).


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- within threshold
end
```
Reason: `DistToSqr` avoids the computationally expensive square root operation required to calculate the exact distance, making it significantly faster for threshold comparisons.


```lua
local threshold = 100
local thresholdSqr = threshold * threshold

if vec1:DistToSqr( vec2 ) < thresholdSqr then
    -- Vectors are closer than 100 units
end
```
Reason: DistToSqr avoids the computationally expensive square root operation that DistTo performs, making it significantly faster for simple threshold checks.


```lua
local isWithinThreshold = vec1:DistToSqr(vec2) <= (threshold * threshold)
```
Reason: `DistToSqr` is significantly faster than calculating the actual distance because it avoids the computationally expensive square root operation.


```lua
vec1:DistToSqr(vec2) < (threshold * threshold)
```
Reason: Using the squared distance avoids the computationally expensive square root operation.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- Vectors are closer than the threshold
end
```
Reason: `Vector:DistToSqr` calculates the squared distance between two vectors, avoiding the computationally expensive square root operation used by `Vector:Distance`.


```lua
for _, ent in ents.Iterator() do
    -- Do something with the entity 'ent'
end
```
Reason: `ents.Iterator()` provides a direct engine-level iterator, avoiding the overhead of creating and populating a new sequential table every time like `ents.GetAll()` does.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: ents.Iterator() is the wiki-recommended approach because it iterates through entities directly without allocating and populating a new table like ents.GetAll() does, making it significantly more memory and CPU efficient.


```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 iterator that avoids the costly table allocation and garbage collection overhead associated with ents.GetAll().


```lua
for _, ent in ents.Iterator() do
    -- Your code here
end
```
Reason: ents.Iterator() avoids the memory allocation and garbage collection overhead of creating a new sequential table on every call, unlike the older ents.GetAll() method.


```lua
for _, ent in ents.Iterator() do
    -- logic here
end
```
Reason: ents.Iterator() is a stateless iterator that avoids allocating a new table every loop, significantly reducing memory usage and garbage collection overhead compared to ipairs(ents.GetAll()).


```lua
local nearbyEnts = ents.FindInSphere(ply:GetPos(), 512)
```
Reason: ents.FindInSphere leverages native engine-level spatial partitioning to perform radius checks significantly faster than iterating over all entities in Lua.


```lua
local function GetEntitiesNearPlayer(ply, radius)
    local nearbyEnts = ents.FindInSphere(ply:GetPos(), radius)

    for i = 1, #nearbyEnts do
        local ent = nearbyEnts[i]
        if ent ~= ply then
            -- Perform cheap operations on nearby entities
        end
    end

    return nearbyEnts
end
```
Reason: ents.FindInSphere runs natively in C++ using the Source engine's internal spatial partitioning, making it dramatically faster than iterating all entities and checking distances in Lua.


```lua
local ents_near = ents.FindInSphere(ply:GetPos(), 300)
for i = 1, #ents_near do
    local ent = ents_near[i]
    if IsValid(ent) and ent ~= ply then
        -- Process nearby entity
    end
end
```
Reason: ents.FindInSphere leverages the engine's internal C++ spatial partitioning to retrieve entities within a radius, drastically reducing overhead compared to iterating over all entities in Lua.


```lua
local nearbyEnts = ents.FindInSphere(ply:GetPos(), 512)
for i = 1, #nearbyEnts do
    local ent = nearbyEnts[i]
    -- Process nearby entity
end
```
Reason: ents.FindInSphere delegates the spatial search to the C++ engine's internal spatial partitioning system, making it significantly faster for radius checks than iterating over all entities in Lua.


```lua
local nearby_ents = ents.FindInSphere(ply:GetPos(), 256)
for i = 1, #nearby_ents do
    local ent = nearby_ents[i]
    -- Process nearby entity
end
```
Reason: `ents.FindInSphere` leverages the engine's C++ spatial partitioning to rapidly cull distant entities, making it vastly more performant than iterating over `ents.GetAll()` in Lua for localized distance checks.


```lua
local function GetPlayersInRadius(pos, radius)
    local players = {}
    local radiusSqr = radius * radius
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            players[#players + 1] = ply
        end
    end
    return players
end
```
Reason: Iterating `player.GetAll()` and comparing squared distances avoids the C++ to Lua table allocation overhead of returning many non-player entities from a spatial query.


```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 relatively small list of players and checking squared distances avoids the costly spatial partition lookups, table allocations, and type-checking for non-player entities that ents.FindInSphere performs.


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

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

    return playersInRadius
end
```
Reason: Iterating `player.GetAll()` and checking squared distances is much faster than `ents.FindInSphere` because it avoids the engine overhead of collecting and building a massive Lua table containing every single entity type within the radius just to discard most of them.


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

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

    return playersInRadius
end
```
Reason: Iterating over the much smaller `player.GetAll()` table and using `DistToSqr` avoids iterating over every single entity on the server, which `ents.FindInSphere` does natively.


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

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

    return found
end
```
Reason: Iterating exclusively through the small list of active players and performing a squared distance check avoids the heavy engine overhead of querying the spatial partition for all map entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numerical for loops have dedicated bytecode instructions in LuaJIT that are more efficiently optimized and avoid the explicit increment and condition checks of a while loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric for loop is generally faster because Lua (and LuaJIT) optimizes its control variables internally in fast registers at the bytecode level, avoiding the explicit increment and condition-check overhead required by a while loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric `for` loop is optimized at the VM level in Lua/LuaJIT, managing the counter and limit internally, which avoids the overhead of manual variable incrementing and explicit conditional checks required by a `while` loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric for loop is generally faster than a while loop because it uses specialized opcodes and handles the incrementation and bounds-checking internally, avoiding the overhead of explicit operations.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric for loop uses specialized bytecode instructions to handle counting natively, making it inherently faster than manually incrementing and checking a variable in a while loop.


```lua
-- Faster Pattern: One hook call with all players
local plys = player.GetAll()
hook.Run("ProcessAllPlayers", plys)

-- Slower Pattern: Hook call per player
local plys = player.GetAll()
for i = 1, #plys do
    hook.Run("ProcessSinglePlayer", plys[i])
end
```
Reason: `hook.Run` has internal overhead from dictionary lookups and iterating over registered functions, making a single hook call significantly faster than invoking the hook for every individual player.


```lua
hook.Add("Tick", "NotifyPlayers", function()
    local players = player.GetAll()
    hook.Run("CustomTick", players)
end)
```
Reason: Calling hook.Run incurs significant overhead from internal lookups, so invoking it once with the table of players is much faster than calling it repeatedly per player.


```lua
local players = player.GetAll()
hook.Run("TickAllPlayers", players)
```
Reason: Calling hook.Run has overhead from looking up the hook name and iterating over registered listener functions, so calling it once and passing the players table avoids multiplying that overhead by the player count.


```lua
-- Faster Pattern: Call hook.Run once and pass all players
local players = player.GetAll()
hook.Run("ProcessAllPlayersTick", players)

-- Slower Pattern: Loop players and call hook.Run per player
local players = player.GetAll()
for i = 1, #players do
    hook.Run("ProcessSinglePlayerTick", players[i])
end
```
Reason: Calling hook.Run once avoids the significant overhead of repeatedly looking up the internal hook table and safely invoking callback functions for every single player each tick.


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

-- Faster pattern: Calling hook.Run once with all players
hook.Add("Tick", "FasterExample", function()
    hook.Run("AllPlayersCustomTick", player.GetAll())
end)
```
Reason: Calling hook.Run incurs internal dictionary lookup and function call overhead, so calling it once with the table of players is significantly faster than repeating that overhead for every individual player.


```lua
local ply = LocalPlayer()
if not IsValid(ply) then return end

local hp = ply: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 results of LocalPlayer() and its Health() method in local variables avoids the overhead of crossing the Lua/C++ boundary multiple times per frame.


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

    local hp = ply: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)
end)
```
Reason: Caching the result of `LocalPlayer():Health()` in a local variable prevents expensive and redundant Lua-to-C++ boundary crossings within the same frame.


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

    local hp = ply:Health()

    draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 50, color_white)
    draw.SimpleText("Remaining: " .. hp, "DermaDefault", 50, 70, color_white)
    draw.SimpleText(hp .. " HP", "DermaDefault", 50, 90, color_white)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids the overhead of making multiple expensive C++ function calls across the Lua-C boundary every frame.


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

    local hp = ply:Health()

    draw.SimpleText( "HP: " .. hp, "Default", 10, 10, color_white )
    draw.SimpleText( "HP: " .. hp, "Default", 11, 11, color_black )
    surface.DrawRect( 10, 30, hp, 10 )
end )
```
Reason: Caching the result in a local variable avoids the performance overhead of repeatedly crossing the Lua-C++ boundary for the same value within a single frame.


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

    local hp = ply:Health()

    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, color_white)
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(10, 50, hp, 20)
end)
```
Reason: Caching the result of LocalPlayer():Health() in a local variable prevents multiple expensive function calls and C-to-Lua boundary crossings in the same frame.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(myColor)
    -- Drawing code here
end)
```
Reason: Calling Color() inside a render loop creates a new table every frame, which causes unnecessary memory allocations and triggers expensive garbage collection overhead.


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

hook.Add("HUDPaint", "OptimizedPaint", function()
    surface.SetDrawColor(drawColor)
end)
```
Reason: Caching the Color object outside the render hook prevents creating a new table every frame, avoiding unnecessary memory allocation and garbage collection overhead.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    -- Use the pre-allocated local variable instead of calling Color() every frame
    surface.SetDrawColor(cached_color)

    -- Alternatively, for pure white, you can use GMod's built-in global constant:
    -- surface.SetDrawColor(color_white)
end)
```
Reason: Caching the color outside the loop (or using the `color_white` constant) prevents a global function call and new table allocation on every frame, eliminating unnecessary CPU overhead and garbage collection stutter.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cachedColor)
    -- Alternatively, surface.SetDrawColor(255, 255, 255) or color_white also bypass new table allocations
end)
```
Reason: Calling Color() inside a render loop constantly allocates new tables, which creates significant memory overhead and triggers frequent, performance-degrading garbage collection cycles.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(paintColor)
    -- ... paint operations here ...
end)
```
Reason: Caching the Color object outside the render loop prevents allocating a new table on every single frame, significantly reducing garbage collection overhead and improving performance.


```lua
local sin = math.sin
for i = 1, 10000 do
    local result = sin(i)
end
```

Reason: Localizing table functions as local variables avoids the overhead of a table lookup on every iteration of the loop.


```lua
local sin = math.sin
for i = 1, 10000 do
    local result = sin(i)
end
```
Reason: Local variable lookups are significantly faster than global table field lookups in Lua and LuaJIT, avoiding a dictionary lookup on every iteration.


```lua
local math_sin = math.sin
for i = 1, 100000 do
    local val = math_sin(i)
end
```
Reason: Local variable lookups use fast register access, completely bypassing the slower hash table lookup required by `math.sin`.


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


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


```lua
local ply = LocalPlayer()

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

    -- Use the cached 'ply' reference here
end)
```
Reason: Caching the entity in a local variable and only updating it when invalid avoids the performance overhead of executing the C-bound LocalPlayer() function on every frame.


```lua
local ply

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

    -- Use ply here
end)
```
Reason: Caching the player entity in a local variable and only calling LocalPlayer() when the cached entity is invalid avoids repeatedly executing the underlying C function.


```lua
local LocalPlayer = LocalPlayer
```
Reason: Assigning the global function to a local variable avoids the expensive string hash lookup in the global environment table (_G) on every call.


```lua
local cachedPly

local function FastLocalPlayer()
    if IsValid(cachedPly) then return cachedPly end
    cachedPly = LocalPlayer()
    return cachedPly
end
```
Reason: Caching the entity in a local variable and only calling LocalPlayer() when the cache is invalid avoids the expensive Lua-to-C++ boundary crossing overhead on subsequent uses.


```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 valid entity reference in a local upvalue avoids the overhead of repeated global table lookups and C++/Lua boundary crossings on subsequent calls.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > (threshold or 0.8) and ply2:GetAimVector():Dot(-dir) > (threshold or 0.8)
end
```
Reason: The dot product of unit vectors directly yields the cosine of the angle between them, providing a cheap way to check directional alignment without the performance overhead of math.acos.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8
    local dir = (ply2:EyePos() - ply1:EyePos()):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 between them, allowing for a fast threshold check without the computational expense of math.acos.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.8
    local dir = (ply2:EyePos() - ply1:EyePos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > threshold and ply2:GetAimVector():Dot(dir) < -threshold
end
```
Reason: The dot product of normalized vectors avoids expensive math.acos computations while accurately checking if each player's aim vector aligns with the direction between their eye positions.


```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 returns the cosine of the angle between them, providing a much faster check against a threshold (e.g., 0.8) without the computational expense of calling math.acos.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    local dir = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dir) > (threshold or 0.8) and ply2:GetAimVector():Dot(-dir) > (threshold or 0.8)
end
```
Reason: The dot product evaluates the alignment of two vectors using simple arithmetic, bypassing the computationally expensive trigonometric math.acos function while achieving the exact same threshold-based cone check.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the metatable lookup overhead required by method calls.


```lua
SomeHelper(ply)
```
Reason: Calling a direct function is generally faster as it avoids the metatable lookup overhead associated with method syntax.


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


```lua
SomeHelper(ply)
```
Reason: Calling a function directly avoids the overhead of a metatable index lookup required by the method call syntax.


```lua
SomeHelper(ply)
```
Reason: `SomeHelper(ply)` avoids the expensive metatable `__index` lookup on the player object required by `ply:SomeHelper()`.


```lua
MsgN("Debug information")
```
Reason: MsgN is a direct C++ engine binding that avoids the overhead of the standard print function, which iterates over all arguments, calls tostring on each, and concatenates them with tabs.


```lua
MsgN("debug line")
```
Reason: MsgN is a direct engine binding that bypasses the Lua-side overhead of the global print function, which performs iteration, type conversion, and concatenation on its arguments.


```lua
MsgN("debug line")
```
Reason: `MsgN` is faster than `print` because it avoids the overhead of Lua-side string formatting, vararg processing, and `tostring` conversions, mapping more directly to the engine's console output function.


```lua
MsgN("Debug line")
```
Reason: MsgN is a direct C-binding that bypasses the overhead of GMod's custom Lua-based print wrapper, which iterates through arguments to apply string conversions and formatting.


```lua
MsgN("Debug line")
```
Reason: MsgN is a direct C++ binding that bypasses the Lua-side overhead of the global print function, which must iterate over its arguments, call tostring on each, and format them.


```lua
local count = #tbl
for i = 1, count do
    local value = tbl[i]
end
```
Reason: A numeric for loop avoids the function call overhead of iterators like `pairs` and `ipairs`, and allows Garry's Mod's underlying LuaJIT to heavily optimize the sequential array access.


```lua
for i = 1, #myTable do
    local value = myTable[i]
end
```
Reason: LuaJIT (used by Garry's Mod) heavily optimizes numeric for loops, avoiding the function call overhead of iterator functions like pairs and ipairs.


```lua
for i = 1, #tbl do
    local value = tbl[i]
end
```
Reason: A numeric for loop is the fastest because it avoids the function call overhead of iterators, and Garry's Mod's LuaJIT compiler can heavily optimize direct array index access.


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


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: A numeric for loop avoids the function call and iterator overhead associated with pairs and ipairs, making it the fastest iteration method in LuaJIT.


```lua
local result = {}
local count = 1
for i = 1, #inputList do
    local val = inputList[i]
    if val.isValid then
        result[count] = val.name
        count = count + 1
    end
end
```
Reason: Hand-written numeric loops avoid intermediate table allocations and function call overhead, allowing LuaJIT to trace and heavily optimize the execution.


```lua
local result = {}
local count = 1
for i = 1, #input do
    local v = input[i]
    if v.isValid then
        result[count] = v.value * 2
        count = count + 1
    end
end
```
Reason: A manual numeric loop with a local insertion counter avoids the function call overhead, closure creation, and intermediate table allocations of functional combinators, allowing LuaJIT to fully trace and heavily optimize the execution.


```lua
local result = {}
local count = 0
for i = 1, #data do
    local v = data[i]
    if v.active then
        count = count + 1
        result[count] = v.id
    end
end
```
Reason: Procedural loops avoid the overhead of intermediate table creations, closure allocations, and nested function calls, allowing LuaJIT to effectively compile and optimize the execution.


```lua
local function filterAndMap(inputTable)
    local result = {}
    local index = 1

    for i = 1, #inputTable do
        local item = inputTable[i]

        -- Filter equivalent
        if item and item.isValid then
            -- Map equivalent
            result[index] = item.value * 2
            index = index + 1
        end
    end

    return result
end
```
Reason: A single imperative loop prevents intermediate table allocations and closure overhead, allowing LuaJIT to compile the code much more efficiently than chained function combinators.


```lua
local function filterMapAlivePlayerNames(players)
    local result = {}
    local index = 1
    for i = 1, #players do
        local ply = players[i]
        if ply:Alive() then
            result[index] = ply:Nick()
            index = index + 1
        end
    end
    return result
end
```
Reason: An imperative loop avoids the closure allocations, function call overhead, and intermediate table creations inherent to DarkRP's multi-pass fn combinators.


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

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

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

hook.Add("Tick", "OptimizedPlayerTick", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        -- Your per-tick player logic here
    end
end)
```
Reason: Caching the player list prevents `player.GetAll()` from allocating a new table and generating garbage collection overhead every single tick, while a numeric for loop iterates the cached array with minimal overhead.


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

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

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

hook.Add("Tick", "CachedPlayerTick", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Tick logic for ply goes here
        end
    end
end)
```
Reason: Caching the array and using a sequential for loop eliminates the overhead of `player.GetAll()` allocating a new table and `ipairs` creating a new iterator every single tick.


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

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

hook.Add("PlayerDisconnected", "UpdatePlayerCacheLeave", function(ply)
    table.RemoveByValue(cached_players, ply)
end)

hook.Add("Tick", "CachedPlayerTick", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Execute per-tick logic here
        end
    end
end)
```
Reason: Calling player.GetAll() every tick allocates a new table each time, causing unnecessary garbage collection and CPU overhead, whereas iterating a pre-allocated indexed table is virtually cost-free.


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

hook.Add("PlayerInitialSpawn", "AddCachedPlayer", function(ply)
    table.insert(cached_players, ply)
end)

hook.Add("PlayerDisconnected", "RemoveCachedPlayer", function(ply)
    table.RemoveByValue(cached_players, ply)
end)

hook.Add("Tick", "OptimizedTickHook", function()
    -- Numeric iteration is faster than ipairs and avoids closure overhead
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Perform per-tick logic here
        end
    end
end)
```
Reason: Calling `player.GetAll()` every tick creates a new table which causes unnecessary memory allocation and frequent garbage collection, whereas caching the players and updating the table on join/leave avoids overhead and allows for faster numeric iteration.


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

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

hook.Add("PlayerDisconnected", "CachePlayerLeave", function(ply)
    table.RemoveByValue(cached_players, ply)
end)

hook.Add("Tick", "OptimizedTick", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Execute per-player logic here
        end
    end
end)
```
Reason: `player.GetAll()` creates and returns a new table upon every call, which causes massive garbage collection overhead when run every tick; maintaining a persistent array and using a numeric `for` loop eliminates table allocations entirely.


```lua
local playerData = {}

-- Write data
playerData[ply] = "temporary_value"

-- Read data
local val = playerData[ply]
```
Reason: Accessing a standard Lua table avoids the expensive `__index` metamethod lookup overhead that occurs when reading fields from a C++ Entity userdata object.


```lua
local tempData = {}

-- Storing the data
tempData[ply] = value

-- Reading the data
local val = tempData[ply]
```
Reason: Using a plain local table avoids the __index metamethod overhead incurred every time you index an entity's userdata object.