Answer must contain 0 through 0 candidate loops.

```lua
local nearby_ents = ents.FindInSphere(ply:GetPos(), 500)
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 Source Engine's internal spatial partitioning tree to quickly query entities in C++, entirely bypassing the severe performance penalty of an O(N) loop and distance calculations across all map entities in Lua.


```lua
local search_radius = 512
local nearby_ents = ents.FindInSphere(ply:GetPos(), search_radius)
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 Source engine's underlying spatial partitioning (octree/BSP) natively in C++, making it vastly faster than Lua-side distance checks or looping through ents.GetAll().


```lua
local pos = ply:GetPos()
local ents_nearby = ents.FindInSphere(pos, 256)
for i = 1, #ents_nearby do
    local ent = ents_nearby[i]
    if IsValid(ent) and ent ~= ply then
        -- Process nearby entity
    end
end
```
Reason: ents.FindInSphere is highly optimized because it performs the spatial radius search directly within the C++ engine using the spatial partition tree, completely bypassing the massive Lua-side overhead of iterating and calculating distances for all entities.


```lua
local function GetEntitiesNearPlayer(ply, radius)
    return ents.FindInSphere(ply:GetPos(), radius)
end
```
Reason: ents.FindInSphere leverages the engine's internal spatial partitioning to quickly find entities within a radius, making it vastly more efficient than iterating through all entities.


```lua
local function GetEntitiesNearPlayer(ply, radius)
    local nearEnts = ents.FindInSphere(ply:GetPos(), radius)
    for i = 1, #nearEnts do
        local ent = nearEnts[i]
        -- Process nearby entity
    end
    return nearEnts
end
```
Reason: ents.FindInSphere leverages the engine's C++ spatial partitioning (Kd-tree/octree) to cull distant objects before creating the Lua table, making it vastly faster than a manual Lua distance check loop.


```lua
local function GetPlayersInSphere(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()` with `DistToSqr` is faster because it completely avoids the overhead of traversing spatial partitions and checking the distance of every non-player entity on the server.


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

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

    return found
end
```
Reason: Iterating the small player.GetAll() table avoids searching through thousands of non-player entities, and using DistToSqr prevents expensive square root math.


```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 `player.GetAll()` and checking squared distances avoids traversing the engine's spatial partition and allocating a table containing every non-player entity in the area.


```lua
local function GetPlayersInRadius(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 `DistToSqr` avoids the overhead of `ents.FindInSphere` checking every entity in the server's spatial partition and prevents large intermediate table allocations.


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

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

    return playersInRange
end
```
Reason: Iterating the small table of connected players and checking squared distances avoids the overhead of spatial partition queries and building large tables of irrelevant entities.


```lua
for i = 1, n do
    -- tight loop code here
end
```
Reason: Garry's Mod uses LuaJIT, which optimizes numeric for loops using highly efficient, dedicated bytecode instructions (FORI/FORL) that handle the increment and bounds check internally, making them faster than while loops that require manual variable increments and condition evaluations.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric `for` loop is generally faster because it is implemented using specialized VM opcodes that handle the iteration and limit checking internally, avoiding the overhead of manual variable increments and condition evaluations required by a `while` loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric `for` loop utilizes dedicated, highly optimized bytecode instructions (FORI/FORL) that handle the counter increment and limit check internally, avoiding the overhead of explicit arithmetic and condition checks required by a `while` loop.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: A numeric for loop is faster because its incrementing and bounds checking are handled internally by dedicated, highly optimized VM bytecodes rather than requiring explicit variable assignments and comparison evaluations in Lua.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: The numeric `for` loop uses dedicated, highly optimized bytecode instructions (like FORPREP and FORLOOP) that handle initialization, incrementing, and bounds checking natively, avoiding the overhead of manual variable manipulation and jump instructions required by a `while` loop.


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

hook.Add("CustomPlayerLogic", "IteratePlayers", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Execute custom logic per player
    end
end)
```
Reason: Calling hook.Run once avoids multiplying the internal hook table lookup and function dispatch overhead by the number of players every single tick.


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

hook.Add("CustomPlayerLogic", "ProcessPlayers", function(plys)
    for i = 1, #plys do
        local ply = plys[i]
        -- Execute custom logic for each player here
    end
end)
```
Reason: Calling hook.Run once per tick eliminates the significant overhead of repeated internal hook table lookups and function dispatches that would occur if it were called inside the player loop.


```lua
hook.Add("Tick", "TriggerAllPlayersTick", function()
    local players = player.GetAll()
    hook.Run("CustomAllPlayersTick", players)
end)

hook.Add("CustomAllPlayersTick", "ProcessPlayerLogic", function(players)
    for i = 1, #players do
        local ply = players[i]
        -- Custom logic for each player
    end
end)
```
Reason: Calling `hook.Run` incurs overhead from table lookups, string hashing, and function dispatches, so doing it once per tick and running a fast numeric loop inside the hook is vastly more performant than paying the hook overhead for every single player.


```lua
-- Slower pattern: Looping players and calling hook.Run per player
hook.Add("Tick", "SlowerPlayerTick", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("CustomPlayerTick", ply)
    end
end)

-- Faster pattern: Calling hook.Run once with all players
hook.Add("Tick", "FasterPlayerTick", function()
    hook.Run("CustomAllPlayersTick", player.GetAll())
end)
```

Reason: Calling `hook.Run` incurs significant overhead from internal string lookups and iterating through hook tables; executing it once per tick rather than once per player avoids multiplying this overhead.


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

-- Slower Pattern: Looping players and calling hook.Run per player
for i = 1, #plys do
    hook.Run("CustomPlayerTick", plys[i])
end

-- Faster Pattern: Calling hook.Run once with all players
hook.Run("CustomAllPlayersTick", plys)
```
Reason: hook.Run incurs internal overhead from dictionary lookups and iterating over registered listener functions; calling it once per tick rather than once per player avoids multiplying this execution cost.


```lua
local hp = LocalPlayer():Health()
draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, color_white)
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(10, 30, hp, 20)
surface.DrawOutlinedRect(10, 30, hp, 20)
```
Reason: Caching the result into a local variable avoids the performance overhead of repeatedly performing C++ function boundary crossings and table lookups 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, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 30, color_white)
    surface.DrawRect(10, 50, hp, 15)
end)
```
Reason: Caching LocalPlayer():Health() into a local variable avoids the performance overhead of repeated global function lookups, C++ metatable accesses, and crossing the Lua-C boundary multiple times in a single render frame.


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

    local hp = ply:Health()

    draw.SimpleText("Health: " .. hp, "DermaDefault", 50, 50, color_white)
    surface.SetDrawColor(255, 0, 0, 255)
    surface.DrawRect(50, 70, hp, 20)
    draw.SimpleText(hp .. "/100", "DermaDefault", 50, 100, color_white)
end)
```
Reason: Caching the health value in a local variable avoids the performance overhead of crossing the Lua-C++ boundary three separate times per frame.


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

    local health = ply:Health()

    draw.SimpleText(health, "DermaDefault", 10, 10, color_white)
    draw.SimpleText(health, "DermaDefault", 10, 30, color_white)
    surface.DrawRect(10, 50, health, 20)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable prevents multiple expensive C++ boundary function calls and table lookups from executing every 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("Shadow: " .. hp, "DermaDefault", 11, 11, color_black)
    surface.DrawRect(10, 30, hp, 10)
end)
```
Reason: Caching the player and health in local variables avoids the overhead of executing multiple expensive Lua-to-C++ boundary crossings every single frame.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cachedColor)
    -- Drawing code goes here
end)
```
Reason: Calling Color() inside a render hook instantiates a new Lua table every frame, causing unnecessary memory allocations and garbage collection spikes; caching it outside the loop avoids this overhead.


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

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


```lua
local white = Color(255, 255, 255) -- Alternatively, use the built-in global 'color_white'

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Calling Color() inside a render loop creates a new table every frame, leading to excessive memory allocation and garbage collection stutter, whereas caching it locally outside the loop reuses the same object.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    -- Alternatively, for white specifically, you can use the built-in global 'color_white'
    surface.SetDrawColor(cachedColor)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Caching the Color object outside the render loop prevents creating a new table every frame, which eliminates unnecessary memory allocations and reduces garbage collection spikes.


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

hook.Add("HUDPaint", "OptimizedPaintLoop", function()
    surface.SetDrawColor(cached_color)
    -- Note: For pure white, you can also use the built-in global `color_white`
end)
```
Reason: Calling Color() creates a new table on every iteration, which wastes memory and causes frequent, expensive garbage collection spikes; caching it outside the loop eliminates this overhead.


```lua
local sin = math.sin
for i = 1, 10000 do
    local val = sin(i)
end
```
Reason: Caching the function reference in a local variable avoids repeated, expensive table lookups during each iteration of the loop.


```lua
local sin = math.sin
for i = 1, 100000 do
    local val = sin(i)
end
```
Reason: Local variables in Lua are accessed via fast register operations, avoiding the expensive hash table lookups required by global environments and table indexing.


```lua
local sin = math.sin
for i = 1, 100000 do
    local result = sin(i)
end
```
Reason: Caching global table functions into local variables avoids the overhead of repeated hash table lookups during loop execution.


```lua
local sin = math.sin
for i = 1, 10000 do
    local val = sin(i)
end
```
Reason: Localizing the function reference avoids the overhead of performing a global environment table lookup for `math` and a hash lookup for `sin` on every iteration.


```lua
local sin = math.sin
for i = 1, 100000 do
    local val = sin(i)
end
```
Reason: Caching the function in a local variable avoids the overhead of a global variable and table index lookup on every iteration of the loop.


```lua
local ply = NULL

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

    -- Use 'ply' here instead of calling LocalPlayer()
end)
```
Reason: Caching the entity object in a local variable avoids the overhead of repeated global table lookups and expensive C++ boundary function calls every frame.


```lua
local ply = LocalPlayer()

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

    -- Use 'ply' here instead of calling LocalPlayer() repeatedly
end)
```
Reason: Caching the player entity in a local upvalue avoids the overhead of a global function lookup and C++ boundary crossing every frame, while the validity check ensures the reference correctly updates once the player is fully initialized.


```lua
local ply
local function GetLocalPlayer()
    if IsValid(ply) then return ply end
    ply = LocalPlayer()
    return ply
end
```
Reason: Caching the valid entity locally avoids the overhead of repeatedly executing the underlying C++ LocalPlayer() function while safely handling the initial NULL entity state during loading.


```lua
local ply

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

    -- Execute logic using 'ply' without repeatedly calling LocalPlayer()
end)
```
Reason: Caching the player entity in a local variable and only calling LocalPlayer() when the cached reference is invalid avoids the continuous performance overhead of crossing the C++ boundary and executing the function.


```lua
local cached_ply = NULL

local function GetCachedLocalPlayer()
    if IsValid(cached_ply) then return cached_ply end
    cached_ply = LocalPlayer()
    return cached_ply
end
```
Reason: Caching the player entity object in a local variable avoids the execution overhead of calling the C++ `LocalPlayer()` function repeatedly, while safely handling the period during client load where the local player is not yet valid.


```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 returns the cosine of the angle between them, allowing you to compare aim directions against the vector between the players using a simple numerical threshold rather than calculating expensive trigonometric functions like math.acos.


```lua
local function AreAimDirectionsFacing(ply1, ply2, dotThreshold)
    -- dotThreshold should be close to -1 (e.g., -0.9). -1 means perfectly opposite directions.
    return ply1:GetAimVector():Dot(ply2:GetAimVector()) <= (dotThreshold or -0.9)
end
```
Reason: The dot product of two normalized vectors yields the cosine of the angle between them, allowing us to check if the directions are roughly opposite by comparing the result directly against a negative threshold instead of using the computationally expensive math.acos function.


```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 two normalized vectors avoids expensive trigonometric functions like math.acos, directly returning a cosine value between -1 and 1 where higher values indicate alignment.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    local dirToPly2 = (ply2:GetShootPos() - ply1:GetShootPos()):GetNormalized()
    return ply1:GetAimVector():Dot(dirToPly2) > (threshold or 0.8) and ply2:GetAimVector():Dot(-dirToPly2) > (threshold or 0.8)
end
```
Reason: Vector dot products directly output the cosine of the angle between normalized vectors, allowing you to bypass computationally expensive math.acos conversions by comparing the result directly against a scalar threshold.


```lua
local function AreLookingAtEachOther(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 directly computes the cosine of the angle between two normalized vectors, allowing you to check if they face the shared direction line by comparing against a pre-calculated scalar threshold and avoiding expensive math.acos calls.


```lua
SomeHelper(ply)
```
Reason: Calling a standalone function directly avoids the performance overhead of a metatable `__index` lookup required by `ply:SomeHelper()`.


```lua
SomeHelper(ply)
```
Reason: Standalone function calls are faster because they avoid the `__index` metatable lookup overhead required when calling methods on an object.


```lua
SomeHelper(ply)
```
Reason: It avoids the metatable indexing overhead required when looking up methods on the player object.


```lua
SomeHelper(ply)
```
Reason: Calling a local function directly avoids the expensive table index and metatable lookups required by object method calls.


```lua
SomeHelper(ply)
```
Reason: Calling a standalone local or global function is faster because it avoids the overhead of a metatable index lookup on the Player userdata object.


```lua
MsgN("debug line")
```
Reason: MsgN is a direct C++ binding to the engine's console output, avoiding the Lua-side overhead of print's formatting, type coercion, and argument separation.


```lua
MsgN("debug line")
```
Reason: `MsgN` is a direct engine C-binding that avoids the overhead of the standard `print` function, which loops through all arguments, calls `tostring` on each, and concatenates them with tabs.


```lua
MsgN("Debug line")
```
Reason: MsgN is a direct C++ binding that avoids the Lua-side overhead of GMod's overridden print function, which iterates through varargs, calls tostring on each argument, and appends tabs.


```lua
MsgN("debug line")
```
Reason: MsgN is a direct C binding that bypasses the argument concatenation and string formatting overhead of print.


```lua
MsgN("Debug line")
```
Reason: MsgN is a direct engine binding that bypasses the Lua-side argument iteration, string conversion, and formatting overhead of Garry's Mod's custom print function.


```lua
for i = 1, #tbl do
    local val = tbl[i]
    -- Do something with val
end
```
Reason: A numeric for loop is the fastest because it avoids the iterator function call overhead of pairs and ipairs, allowing Garry's Mod's LuaJIT compiler to heavily optimize the execution.


```lua
local len = #myTable
for i = 1, len do
    local value = myTable[i]
end
```
Reason: Numeric for loops are the fastest in GMod's LuaJIT because they avoid the function call overhead of iterators and compile most efficiently to native code.


```lua
for i = 1, #tbl do
    local value = tbl[i]
end
```
Reason: A numeric for loop avoids the function call and iterator overhead associated with pairs and ipairs, allowing Garry's Mod's LuaJIT engine to compile it into the fastest possible machine code.


```lua
for i = 1, #tbl do
    local value = tbl[i]
end
```
Reason: A numeric for loop is the fastest in Garry's Mod because LuaJIT can trace and optimize it best without the iterator function call overhead associated with pairs or ipairs.


```lua
for i = 1, #tbl do
    local val = tbl[i]
end
```
Reason: Garry's Mod runs on LuaJIT, which heavily optimizes numeric for loops and direct array indexing, completely avoiding the expensive iterator function call overhead associated with pairs and ipairs.


```lua
local function getActivePlayerNames(players)
    local result = {}
    local count = 0
    for i = 1, #players do
        local ply = players[i]
        -- Filter step
        if IsValid(ply) and ply:Alive() then
            count = count + 1
            -- Map step
            result[count] = ply:Nick()
        end
    end
    return result
end
```
Reason: Fusing the filter and map operations into a single imperative loop with a local counter avoids the intermediate table allocations, heavy closure creation, and function call overhead of the `fn` library, allowing LuaJIT to seamlessly trace and compile the code.


```lua
local inputList = {1, 2, 3, 4, 5, 6, 7, 8}
local resultList = {}
local count = 1

for i = 1, #inputList do
    local val = inputList[i]
    if val % 2 == 0 then
        resultList[count] = val * 2
        count = count + 1
    end
end
```
Reason: Manual loops with inline conditions fuse operations into a single pass, completely avoiding the intermediate table allocations and closure execution overhead inherent to functional combinators like DarkRP's `fn` library.


```lua
local result = {}
local count = 1
for i = 1, #input_list do
    local item = input_list[i]
    if item > 10 then
        result[count] = item * 2
        count = count + 1
    end
end
```
Reason: A single-pass numeric for-loop avoids the closure allocations, function call overhead, and intermediate table creations of DarkRP's fn combinators.


```lua
local function fastTransform(items)
    local result = {}
    local count = 0
    for i = 1, #items do
        local item = items[i]
        if item.isValid then
            count = count + 1
            result[count] = item.value * 2
        end
    end
    return result
end
```
Reason: An imperative numeric loop with a manual counter avoids the intermediate table allocations and heavy closure overhead of functional combinators, allowing Garry's Mod's LuaJIT engine to fully optimize and trace the execution.


```lua
-- DarkRP fn approach (Slow: creates intermediate tables and high closure overhead):
-- local activeIDs = fn.Map(function(p) return p:UserID() end, fn.Filter(function(p) return p:Alive() end, player.GetAll()))

-- Faster approach: Single-pass imperative loop
local activeIDs = {}
local count = 1
local plys = player.GetAll()

for i = 1, #plys do
    local ply = plys[i]
    if ply:Alive() then
        activeIDs[count] = ply:UserID()
        count = count + 1
    end
end
```
Reason: A single imperative loop avoids intermediate table allocations and anonymous function call overhead by processing the filter and map together in one pass.


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

hook.Add("PlayerInitialSpawn", "UpdatePlayerCacheJoin", function()
    cachedPlayers = player.GetAll()
end)

hook.Add("PlayerDisconnected", "UpdatePlayerCacheLeave", function()
    -- Wait until the next frame to ensure the player is removed from the global pool
    timer.Simple(0, function()
        cachedPlayers = player.GetAll()
    end)
end)

hook.Add("Think", "OptimizedPlayerThink", function()
    for i = 1, #cachedPlayers do
        local ply = cachedPlayers[i]
        if IsValid(ply) then
            -- Put your per-tick player logic here
        end
    end
end)
```
Reason: Calling player.GetAll() every tick forces the engine to allocate a new table 66 times a second, causing unnecessary garbage collection spikes; caching it and using a numeric for loop achieves zero-allocation 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()
    -- Use a 0-second timer because the player might still be in player.GetAll() during the disconnect hook
    timer.Simple(0, UpdatePlayerCache)
end)

hook.Add("Tick", "OptimizedTickTask", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Perform tick operations on ply
        end
    end
end)
```
Reason: Calling player.GetAll() every tick allocates a new table and creates constant garbage collection overhead, whereas refreshing a cached array on join/leave and iterating it with a numeric for loop drastically reduces memory allocations and CPU usage.


```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("Tick", "OptimizedTick", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Your per-tick logic here
        end
    end
end)
```
Reason: Caching the array and using a numeric for-loop avoids allocating a new table and iterator closure every single tick, drastically reducing garbage collection overhead and CPU usage.


```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("Tick", "OptimizedPlayerTick", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Perform per-tick player logic here
        end
    end
end)
```
Reason: Caching the player array and iterating over it with a numeric for loop avoids the performance hit of table allocations from player.GetAll() and the function call overhead of the ipairs iterator running every single 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("Tick", "OptimizedTick", function()
    for i = 1, #cached_players do
        local ply = cached_players[i]
        if IsValid(ply) then
            -- Perform per-tick operations here
        end
    end
end)
```
Reason: Calling `player.GetAll()` every tick dynamically allocates a new table which causes unnecessary garbage collection overhead, whereas maintaining a cached sequential array and iterating it with a numeric for loop produces zero allocations per tick and is highly optimized in LuaJIT.


```lua
local playerData = {}

-- Write
playerData[ply] = value

-- Read
local val = playerData[ply]
```
Reason: Indexing a local Lua table avoids the expensive userdata metatable lookups and C-API boundary crossings required when accessing fields directly on the player entity object.


```lua
local playerData = {}

-- Write
playerData[ply] = "value"

-- Read
local value = playerData[ply]
```
Reason: Indexing a local Lua table directly bypasses the expensive C++ `__index` metamethod overhead that is invoked every time you read a field from a Player userdata object.


```lua
local playerData = {}

-- Write
playerData[ply] = value

-- Read
local val = playerData[ply]
```
Reason: Reading from a standard Lua table avoids the expensive `__index` metatable lookup and C++ boundary crossing associated with accessing fields on an Entity userdata object.


```lua
local playerData = {}

-- Writing data
playerData[ply] = value

-- Reading data
local val = playerData[ply]
```
Reason: Indexing a plain Lua table avoids the expensive C++ boundary crossing and metatable lookups associated with Entity userdata objects.


```lua
local playerData = {}

-- Writing data
playerData[ply] = value

-- Reading data
local value = playerData[ply]
```
Reason: Using a standard local Lua table bypasses the expensive `__index` metamethod overhead that occurs when reading fields from Player userdata objects.


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

for i = 1, #fastTable do
    local value = fastTable[i]
    -- Process value
end
```
Reason: Sequential number-indexed arrays can be iterated using a numeric for loop, which directly accesses the contiguous array part of the table in memory and avoids the expensive hash map lookups required when using pairs() on string-keyed maps.


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

for i = 1, #fast_collection do
    local current_value = fast_collection[i]
    -- Process current_value
end
```
Reason: Sequential number-indexed arrays allow iteration using a numeric for loop and direct array-part memory access, which is heavily optimized by LuaJIT compared to the slower hash lookups and `pairs()` iterator required for string-keyed maps.


```lua
local sequential_array = {
    "Entity1",
    "Entity2",
    "Entity3"
}

for i = 1, #sequential_array do
    local value = sequential_array[i]
    -- Iteration is fast and predictable
end
```
Reason: Sequential number-indexed arrays allow the use of a simple numeric for loop, which is heavily optimized by LuaJIT and completely avoids the expensive hash-bucket lookups required when iterating string-keyed maps with pairs().


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

for i = 1, #fastArray do
    local value = fastArray[i]
end
```
Reason: Sequential number-indexed arrays iterated with a numeric for loop avoid the overhead of hash lookups and pairs(), allowing LuaJIT to heavily optimize memory access and execution speed.


```lua
local fast_array = {
    "first_value",
    "second_value",
    "third_value"
}

for i = 1, #fast_array do
    local val = fast_array[i]
end
```
Reason: Sequential number-indexed arrays are iterated using a numeric for loop, which directly accesses the contiguous array part of the table in memory, entirely avoiding the expensive hash map lookups and iterator function overhead associated with `pairs()` on string-keyed maps.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate numbers avoids the overhead of table indexing and creation associated with Color objects, allowing LuaJIT to optimize the call more effectively.


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


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


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing primitive numbers avoids the table indexing overhead and type checking associated with passing a Color object.


```lua
surface.SetDrawColor(255, 255, 255, 255)
```
Reason: Passing separate primitive numbers avoids the overhead of Lua table lookups (`lua_getfield`) on the C++ side and prevents table allocations if the color were created inline.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:0:123456'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite avoids network round-trip overhead entirely by reading and writing directly to a local file, resulting in lower latency than remote MySQL.


```lua
local data = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:1234567';")
if data then
    PrintTable(data)
end
```
Reason: Local SQLite eliminates network round-trip delays entirely, resulting in fundamentally lower latency for reads and writes compared to communicating with a remote MySQL server.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:12345678'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite avoids network round-trip overhead entirely, providing significantly lower read/write latency compared to a remote MySQL database.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:0:12345'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite avoids network round-trip delays by reading and writing directly to the server's local disk, resulting in significantly lower latency than remote MySQL.


```lua
local result = sql.Query("SELECT * FROM player_data WHERE steamid = 'STEAM_0:1:1234567'")
if result then
    PrintTable(result)
end
```
Reason: Local SQLite avoids network round-trip overhead entirely, resulting in much lower read/write latency than a remote MySQL connection.


```lua
local function GetCachedSteamID(ply)
    local steamID = ply._cachedSteamID
    if not steamID then
        steamID = ply:SteamID()
        ply._cachedSteamID = steamID
    end
    return steamID
end
```
Reason: Caching the SteamID directly on the player table prevents repeated expensive C++ boundary crossings and new string allocations.


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

    id = ply:SteamID()
    ply.CachedSteamID = id
    return id
end
```
Reason: Reading a cached Lua table field avoids the expensive C/Lua boundary crossing overhead inherent in calling engine methods, which LuaJIT can then compile into extremely fast machine code.


```lua
local steamIDCache = {}

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

local function GetCachedSteamID(ply)
    local steamID = steamIDCache[ply]
    if not steamID then
        steamID = ply:SteamID()
        steamIDCache[ply] = steamID
    end
    return steamID
end
```
Reason: A local Lua table avoids the expensive C++ boundary crossing of calling ply:SteamID() and skips the __index metamethod overhead that occurs when storing caching variables directly on the player entity userdata.


```lua
local function GetCachedSteamID(ply)
    local sid = ply.CachedSteamID
    if not sid then
        sid = ply:SteamID()
        ply.CachedSteamID = sid
    end
    return sid
end
```
Reason: Storing the result in a Lua table field avoids the expensive C++ boundary crossing overhead of repeatedly calling the engine function.


```lua
local function GetCachedSteamID(ply)
    local steamID = ply._CachedSteamID
    if steamID then return steamID end

    steamID = ply:SteamID()
    ply._CachedSteamID = steamID
    return steamID
end
```
Reason: Accessing a Lua table field directly avoids the overhead of crossing the C++ boundary required by the native ply:SteamID() function call.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "piece"
end
local finalString = table.concat(pieces)
```
Reason: Using table.concat joins the strings in a single pass, completely avoiding the exponential memory reallocation and garbage collection overhead of creating intermediate strings with the .. operator.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece"
end
local result = table.concat(pieces)
```
Reason: `table.concat` allocates memory once for the final string, avoiding the quadratic time complexity and excessive garbage collection overhead of creating intermediate strings with repeated `..` concatenation.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "small_string"
end
local finalString = table.concat(pieces)
```
Reason: table.concat allocates memory for the final string just once, avoiding the heavy garbage collection overhead of creating thousands of intermediate strings.


```lua
local buffer = {}
for i = 1, 10000 do
    buffer[#buffer + 1] = "piece_" .. i
end
local finalString = table.concat(buffer)
```
Reason: table.concat allocates memory for the final string only once, avoiding the quadratic time complexity and excessive garbage collection overhead caused by repeatedly creating intermediate strings with the .. operator.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "small_piece_" .. i
end
local final_string = table.concat(pieces)
```
Reason: `table.concat` avoids the creation of thousands of intermediate string objects, eliminating massive memory reallocation and garbage collection overhead.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Calling the `surface` functions directly bypasses the Lua function overhead and radius-checking conditional logic inside `draw.RoundedBox`.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, width, height)
```
Reason: Directly calling the surface library's C++ functions bypasses the overhead of the draw library's Lua wrapper and its conditional logic for corner calculations.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, width, height)
```
Reason: Calling the surface library functions directly avoids the Lua wrapper overhead and radius conditional checks of draw.RoundedBox.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: Calling the surface library directly avoids the Lua-side overhead in draw.RoundedBox, which internally checks the radius and unpacks the color table before calling these exact same engine functions.


```lua
surface.SetDrawColor(color)
surface.DrawRect(x, y, w, h)
```
Reason: Calling the `surface` functions directly avoids the internal type checking, table lookups, and branching overhead of the `draw.RoundedBox` wrapper.


```lua
surface.SetFont( "DermaDefault" )
surface.SetTextColor( 255, 255, 255, 255 )
surface.SetTextPos( 10, 10 )
surface.DrawText( "Your single-line string here" )
```
Reason: Using the raw surface API directly avoids the mathematical alignment calculations, multiline handling, and Lua function overhead present in wrappers like draw.SimpleText or draw.DrawText.


```lua
hook.Add("HUDPaint", "FastTextDrawing", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(50, 50)
    surface.DrawText("This is the fastest text drawing method.")
end)
```
Reason: Using native surface.* functions is the fastest approach because it avoids the extra table lookups, alignment math, and function wrapper overhead introduced by the draw.* library.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Hello World")
```
Reason: The `surface.*` functions are direct bindings to the C++ engine and avoid the extra Lua overhead, function calls, and table lookups present in the `draw.*` wrapper library.


```lua
hook.Add("HUDPaint", "FastestTextDraw", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(100, 100)
    surface.DrawText("Direct surface drawing is the fastest approach")
end)
```
Reason: Using `surface.*` functions directly bypasses the additional Lua wrapper overhead, argument checking, and alignment math present in `draw.DrawText` and `draw.SimpleTextOutlined`.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Faster single-line string")
```
Reason: surface.DrawText is a direct engine C++ binding that avoids the overhead of alignment math, newline parsing, and extra Lua function calls found in the draw library wrappers.


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


```lua
#
```
Reason: The length operator `#` is natively built into Lua and is vastly more performant than Garry's Mod specific functions like `table.Count` for sequential tables.


```lua
#tbl
```
Reason: The `#` length operator is a native language feature that is the standard and most performant way to get the length of a sequential table in Lua.


```lua
#tbl
```
Reason: The `#` operator is the native Lua 5.1 length operator and is significantly faster than iteration-based functions like `table.Count` for sequential tables.


```lua
#myTable
```
Reason: The # operator is the standard, most performant way to get the length of a sequential array-like table in Lua 5.1 (used by Garry's Mod), whereas functions like table.Count iterate the entire table and are meant for non-sequential dictionaries.


```lua
t = {}
```
Reason: Reassigning to a new table is an O(1) operation, whereas table.Empty(t) is an O(N) operation because it must iterate through every key-value pair to set them to nil.


```lua
t = {}
```
Reason: Allocating a new empty table is an O(1) operation that avoids the O(n) overhead of iterating through and deleting every key-value pair from the existing table.


```lua
t = {}
```
Reason: Assigning a new table is an O(1) operation, which avoids the O(N) overhead of `table.Empty()` iterating through every key with `pairs`.


```lua
t = {}
```
Reason: Reassigning to a new table is an O(1) operation that simply allocates an empty table, avoiding the O(N) iteration overhead of table.Empty() setting every key to nil.


```lua
t = {}
```
Reason: `t = {}` is an O(1) operation that immediately creates a new table reference, whereas `table.Empty(t)` is an O(n) operation that must iterate through and nil every existing key.


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

if mySet["apple"] then
    -- Value exists
end
```
Reason: Table key lookups operate in O(1) time as a hash map, whereas table.HasValue performs an O(n) linear search.


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

if mySet["banana"] then
    -- Value exists
end
```
Reason: Table key lookups use a hash map providing O(1) access time, whereas table.HasValue performs an O(n) linear search by iterating over all elements.


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

if fastSet["apple"] then
    -- Value exists
end
```
Reason: Direct table key lookups use hash maps with O(1) time complexity, avoiding the slow O(n) sequential iteration of table.HasValue.


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

if mySet["value1"] then
    -- The value exists in the set
end
```
Reason: Dictionary key lookup is O(1) time complexity, whereas table.HasValue is O(n) because it iterates sequentially through the table.


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

local function checkValue(val)
    if mySet[val] then
        return true
    end
    return false
end
```
Reason: Dictionary key lookups operate in O(1) time complexity using hash tables, whereas table.HasValue performs an O(n) linear search through the sequential list.


```lua
local myTable = {
    field1 = 1,
    field2 = 2,
    field3 = 3
}
```
Reason: Defining fields directly in the constructor allows LuaJIT to pre-allocate the exact memory needed, avoiding the performance overhead of dynamic table resizing and rehashing that occurs when assigning fields individually to an empty table.


```lua
local tbl = {
    field1 = "value1",
    field2 = "value2"
}
```
Reason: Defining fields inside the table constructor pre-allocates the necessary memory size, avoiding costly table reallocations that occur when adding fields to an empty table.


```lua
local tbl = {
    field1 = "value1",
    field2 = "value2",
    field3 = "value3"
}
```
Reason: Defining fields directly in the constructor pre-allocates the table to the correct size, avoiding costly memory reallocations that occur when assigning new keys to an initially empty table.


```lua
local myTable = { x = 10, y = 20, z = 30 }
```
Reason: Defining fields inside the table constructor allows Lua to pre-allocate the exact size needed, avoiding the performance penalty of multiple reallocations and rehashing that occurs when assigning fields to an initially empty table.


```lua
local myTable = { x = 10, y = 20, z = 30 }
```
Reason: The table constructor pre-allocates the correct amount of memory for the fields, avoiding the overhead of resizing and rehashing that occurs when adding fields sequentially to an empty table.


```lua
local random_element = tbl[math.random(#tbl)]
```
Reason: table.Random iterates through the entire table to support non-sequential keys, while math.random(#tbl) provides direct array indexing in O(1) time.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Accessing a random integer index directly avoids the O(n) iteration overhead of `table.Random`, which internally iterates through the entire table using `pairs` to support non-sequential keys.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random uses table.Count and a pairs loop which is O(N), whereas math.random with the length operator provides direct O(1) indexing for sequential tables.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: table.Random is O(n) because it uses table.Count and pairs to iterate and support non-sequential keys, whereas direct index access with math.random is O(1).


```lua
local randomElement = myTable[math.random(#myTable)]
```
Reason: Direct indexing using the length operator is O(1) for sequential tables, whereas table.Random uses pairs iteration which is O(N).


```lua
x * x
```
Reason: Simple multiplication avoids the overhead of function calls (`math.pow`) or exponentiation operators (`^`), allowing LuaJIT to compile it directly into a single, highly optimized CPU multiplication instruction.


```lua
local result = x * x
```
Reason: Multiplication is faster than using the exponent operator (`x ^ 2`) or function calls (`math.pow(x, 2)`) in LuaJIT.


```lua
x * x
```
Reason: Direct multiplication is significantly faster than using the exponentiation operator (`x ^ 2`) or `math.pow` because it avoids function call overhead and complex exponentiation routines, especially under LuaJIT.


```lua
x * x
```
Reason: Direct multiplication is faster than using the power operator (^) or math.pow, especially under LuaJIT which Garry's Mod uses.


```lua
local squared = x * x
```
Reason: Direct multiplication avoids the overhead of the `^` operator or `math.pow` function calls, allowing LuaJIT to compile it into a single fast arithmetic instruction.


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

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


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Do something with ply
end
```
Reason: `player.GetAll()` returns a sequentially indexed table, so using `ipairs` is standard and more efficient than `pairs` in modern Garry's Mod Lua.


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

```lua
for _, ply in player.Iterator() do
    -- Your code here
end
```
Reason: `player.Iterator()` is the modern, optimized method for iterating over connected players because it avoids allocating a new table in memory on every call, significantly improving performance and reducing garbage collection overhead compared to `player.GetAll()`.


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


```lua
for _, ply in ipairs(player.GetAll()) do
    -- ...
end
```
Reason: Using `ipairs` is faster and more optimal than `pairs` for iterating over sequentially indexed tables like the one returned by `player.GetAll()`.


Updates predicted state every pass and gates only the one-shot effect.

```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + 0.5)

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectdata)
    end
end
```
Reason: SetNextPrimaryFire must run unconditionally for the prediction system to properly synchronize the firing rate between client and server, while util.Effect is wrapped in IsFirstTimePredicted() to prevent the client from drawing the effect multiple times during prediction corrections.


```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)

    if IsFirstTimePredicted() then
        local effectData = EffectData()
        effectData:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectData)
    end
end
```
Reason: SetNextPrimaryFire is run unconditionally so the weapon timer stays synchronized across all prediction passes, while util.Effect is wrapped in IsFirstTimePredicted so visual effects only trigger once instead of spamming during prediction corrections.


```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + 0.5)

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectdata)
    end
end
```
Reason: The attack logic updates NextPrimaryFire globally to maintain prediction flow, while visual effects are wrapped in IsFirstTimePredicted() to prevent duplication during prediction recalculations.


```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)

    if IsFirstTimePredicted() then
        local effectData = EffectData()
        effectData:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectData)
    end
end
```
Reason: SetNextPrimaryFire must execute unconditionally to maintain synchronized firing state across prediction passes, while util.Effect is guarded by IsFirstTimePredicted to prevent visual spam during client-side prediction corrections.


```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + 0.1)

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectdata)
    end
end
```
Reason: SetNextPrimaryFire must run on all prediction passes to keep the client's fire rate state aligned with the server, while IsFirstTimePredicted ensures the muzzle flash effect is only created once per shot, preventing visual spam when prediction re-runs.


Does not show the required shared loading and server-authoritative action.

```lua
AddCSLuaFile()

if SERVER then
    function ApplyDamage(ply, ent, amount)
        if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
            ent:TakeDamage(amount, ply, ply)
        end
    end
end
```
Reason: AddCSLuaFile() ensures the client downloads the shared script, while the if SERVER block restricts the ApplyDamage function and its validity checks to run exclusively on the authoritative server.


Loading is correct, but server authority or caller authorization is incomplete.

```lua
if SERVER then
    AddCSLuaFile("myaddon/shared.lua")
end
include("myaddon/shared.lua")

function ApplyDamage(ply, ent, amount)
    if SERVER then
        if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
            ent:TakeDamage(amount, ply, ply)
        end
    end
end
```
Reason: AddCSLuaFile marks the file to be sent to clients from the server, include executes the file on both realms, and the SERVER block restricts the damage logic to the server after verifying the player's validity.


```lua
AddCSLuaFile()

function ApplyDamage(ply, ent, damage)
    if SERVER then
        if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
            ent:TakeDamage(damage, ply, ply)
        end
    end
end
```
Reason: AddCSLuaFile() marks the script to be downloaded by clients so both realms execute it, while the SERVER block restricts the execution of damage logic to the server after validating the player.


```lua
if SERVER then
    AddCSLuaFile("myaddon/shared.lua")
end
include("myaddon/shared.lua")

if SERVER then
    function ApplyDamage(ply, ent, damage)
        if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
            ent:TakeDamage(damage, ply, ply)
        end
    end
end
```
Reason: AddCSLuaFile ensures clients download the shared file while include executes it on both realms, and the SERVER block restricts the damage action and player validation to the server to prevent client-side exploits.


```lua
AddCSLuaFile("myaddon/shared.lua")
include("myaddon/shared.lua")

function ApplyDamage(ply, ent, damage)
    if SERVER then
        if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
            ent:TakeDamage(damage, ply, ply)
        end
    end
end
```
Reason: AddCSLuaFile marks the file to be downloaded by clients and include executes it on the current realm, while the SERVER block ensures damage is only dealt authoritatively after verifying the player's validity.


Seeds and maintains an addon set, then uses squared distance in Think.

```lua
local my_addon_ents = {}
local SEARCH_RADIUS_SQR = 500 * 500 -- Example radius squared

-- Initialization: Seed the keyed set for entities that already exist (e.g. on script reload)
for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
    my_addon_ents[ent] = true
end

-- Registration: Maintain the set as entities appear
hook.Add("OnEntityCreated", "MyAddon_TrackCreated", function(ent)
    -- A 0-second timer ensures the entity's class is fully initialized by the engine
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            my_addon_ents[ent] = true
        end
    end)
end)

-- Cleanup: Maintain the set as entities disappear
hook.Add("EntityRemoved", "MyAddon_TrackRemoved", function(ent)
    my_addon_ents[ent] = nil
end)

-- Think hook: The hot loop
hook.Add("Think", "MyAddon_ProcessInRange", function()
    local target = Entity(1) -- Placeholder for your actual target entity
    if not IsValid(target) then return end

    local targetPos = target:GetPos()

    for ent in pairs(my_addon_ents) do
        if IsValid(ent) then
            -- Use squared distance to avoid expensive math.sqrt calculations each tick
            if targetPos:DistToSqr(ent:GetPos()) <= SEARCH_RADIUS_SQR then
                -- TODO: Do something with the entity within the radius
            end
        else
            -- Failsafe cleanup in case an entity became NULL without triggering EntityRemoved
            my_addon_ents[ent] = nil
        end
    end
end)
```
Reason: Caching specific entities in a keyed set maintained by engine hooks prevents O(N) global map iteration every tick, while DistToSqr avoids costly square root operations, drastically optimizing the Think hook's performance.


```lua
local my_ents = {}
local target = NULL -- Assumed to be set elsewhere
local radius_sq = 500 * 500

local function InitSet()
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        my_ents[ent] = true
    end
end
hook.Add("InitPostEntity", "MyAddon_InitSet", InitSet)
InitSet() -- Seed existing entities if the script is loaded mid-game

hook.Add("OnEntityCreated", "MyAddon_AddEnt", function(ent)
    -- Delay class check by a tick to ensure the entity is fully initialized
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            my_ents[ent] = true
        end
    end)
end)

hook.Add("EntityRemoved", "MyAddon_RemoveEnt", function(ent)
    if my_ents[ent] then
        my_ents[ent] = nil
    end
end)

hook.Add("Think", "MyAddon_ThinkLoop", function()
    if not IsValid(target) then return end

    local target_pos = target:GetPos()

    for ent in pairs(my_ents) do
        if IsValid(ent) then
            if target_pos:DistToSqr(ent:GetPos()) <= radius_sq then
                -- Entity is within radius, process it here
            end
        else
            -- Cleanup stale references just in case
            my_ents[ent] = nil
        end
    end
end)
```
Reason: Caching specific entities in a keyed table via creation/removal hooks prevents iterating over all map entities each tick, while DistToSqr skips the expensive square root operation of standard distance checks.


```lua
local my_addon_ents = {}
local target_entity = NULL -- Replace with your actual target entity
local RADIUS_SQR = 500 * 500 -- Squared radius for distance checks

-- Initialization: Seed the keyed set with already existing entities
local function SeedEntities()
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        if IsValid(ent) then
            my_addon_ents[ent] = true
        end
    end
end
hook.Add("InitPostEntity", "MyAddon_Init", SeedEntities)
SeedEntities() -- Called immediately to account for Lua reloads mid-game

-- Registration: Maintain the set as entities appear and disappear
hook.Add("OnEntityCreated", "MyAddon_TrackCreated", function(ent)
    -- timer.Simple 0 is used because GetClass() may not be populated on the exact tick of creation
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            my_addon_ents[ent] = true
        end
    end)
end)

hook.Add("EntityRemoved", "MyAddon_TrackRemoved", function(ent)
    my_addon_ents[ent] = nil
end)

-- Cleanup: Remove all hooks and clear the cache
local function CleanupMyAddon()
    hook.Remove("InitPostEntity", "MyAddon_Init")
    hook.Remove("OnEntityCreated", "MyAddon_TrackCreated")
    hook.Remove("EntityRemoved", "MyAddon_TrackRemoved")
    hook.Remove("Think", "MyAddon_HotLoop")
    my_addon_ents = {}
end

-- Think hook: The hot loop utilizing the cached set and squared distance
hook.Add("Think", "MyAddon_HotLoop", function()
    if not IsValid(target_entity) then return end

    local target_pos = target_entity:GetPos()

    for ent in pairs(my_addon_ents) do
        if IsValid(ent) then
            if target_pos:DistToSqr(ent:GetPos()) <= RADIUS_SQR then
                -- Entity is within the radius, perform logic here
            end
        else
            -- Failsafe removal in case EntityRemoved missed it
            my_addon_ents[ent] = nil
        end
    end
end)
```
Reason: Caching specific entities into a keyed table on creation avoids calling O(N) global entity scans like `ents.FindByClass` on every tick, while `DistToSqr` skips the expensive square root calculation required by normal distance functions in the hot loop.


```lua
local myAddonEnts = {}

-- 1. Initialization: Seed the keyed set with entities that already exist
local function SeedEntities()
    myAddonEnts = {}
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        if IsValid(ent) then
            myAddonEnts[ent] = true
        end
    end
end
SeedEntities() -- Call immediately for Lua reloads
hook.Add("InitPostEntity", "MyAddon_SeedEntities", SeedEntities)

-- 2. Registration: Maintain the set as entities appear
hook.Add("OnEntityCreated", "MyAddon_RegisterEntity", function(ent)
    -- A 0-second timer is required as GetClass() may not be fully initialized on creation
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            myAddonEnts[ent] = true
        end
    end)
end)

-- 3. Cleanup: Maintain the set as entities disappear
hook.Add("EntityRemoved", "MyAddon_CleanupEntity", function(ent)
    -- Keyed table allows O(1) removal without needing to check the class
    myAddonEnts[ent] = nil
end)

-- 4. Think Hook: Use squared distance in the hot loop
local target = NULL -- Replace this with your actual target entity
local searchRadius = 500
local searchRadiusSqr = searchRadius * searchRadius

hook.Add("Think", "MyAddon_RadiusCheck", function()
    if not IsValid(target) then return end

    local targetPos = target:GetPos()

    for ent in pairs(myAddonEnts) do
        -- Safety check in case an entity became invalid but wasn't caught by EntityRemoved yet
        if IsValid(ent) then
            -- Squared distance avoids the costly square root calculation of normal distance checks
            if ent:GetPos():DistToSqr(targetPos) <= searchRadiusSqr then
                -- ent is within radius, perform logic here
            end
        else
            myAddonEnts[ent] = nil
        end
    end
end)
```
Reason: Utilizing a keyed hash map updated via entity lifecycle hooks avoids scanning the entire entity list every tick, while DistToSqr prevents expensive square root math during the Think loop.


```lua
local myAddonEnts = {}
local SEARCH_RADIUS_SQR = 250000 -- Example: 500^2

-- Initialization: Seed the keyed set for entities that already exist
for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
    if IsValid(ent) then
        myAddonEnts[ent] = true
    end
end

-- Registration: Add to the set as entities appear
hook.Add("OnEntityCreated", "MyAddon_RegisterEnt", function(ent)
    -- 0-second timer ensures the scripted entity has fully initialized its class string
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            myAddonEnts[ent] = true
        end
    end)
end)

-- Cleanup: Remove from the set as entities disappear
hook.Add("EntityRemoved", "MyAddon_CleanupEnt", function(ent)
    if myAddonEnts[ent] then
        myAddonEnts[ent] = nil
    end
end)

-- Think hook: Hot loop using squared distance
hook.Add("Think", "MyAddon_ProximityCheck", function()
    local target = Entity(1) -- Replace with your actual target entity
    if not IsValid(target) then return end

    local targetPos = target:GetPos()

    for ent in pairs(myAddonEnts) do
        if not IsValid(ent) then
            myAddonEnts[ent] = nil
            continue
        end

        if targetPos:DistToSqr(ent:GetPos()) <= SEARCH_RADIUS_SQR then
            -- Entity is within radius; execute logic here
        end
    end
end)
```
Reason: Caching entities in a keyed table and using squared distance avoids the massive O(n) overhead of searching all map entities and computing expensive square roots every tick.


Pre-spawn hook satisfies 7/8 throttling checks.

```lua
local playerAttempts = {}

hook.Add("PlayerSpawnProp", "LimitPropSpawnsPerSecond", function(ply, model)
    if not IsValid(ply) then return end

    local currentWindow = math.floor(CurTime())
    local state = playerAttempts[ply]

    if not state then
        state = {window = currentWindow, count = 0}
        playerAttempts[ply] = state
    end

    if state.window ~= currentWindow then
        state.window = currentWindow
        state.count = 0
    end

    state.count = state.count + 1

    if state.count > 10 then
        return false
    end
end)

hook.Add("PlayerDisconnected", "CleanupPropSpawnsState", function(ply)
    playerAttempts[ply] = nil
end)
```
Reason: Returning false from `PlayerSpawnProp` denies the spawn before the entity is created, omitting a return when under budget preserves other hooks, `math.floor(CurTime())` tracks the fixed one-second window, and `PlayerDisconnected` cleans up the tracked state.


Pre-spawn hook satisfies 4/8 throttling checks.

```lua
local spawnAttempts = {}

hook.Add("PlayerSpawnProp", "PropSpawnRateLimiter", function(ply, model)
    local plyID = ply:SteamID()
    local currentTime = CurTime()

    if not spawnAttempts[plyID] or (currentTime - spawnAttempts[plyID].windowStart >= 1) then
        spawnAttempts[plyID] = { count = 0, windowStart = currentTime }
    end

    if spawnAttempts[plyID].count >= 10 then
        return false
    end

    spawnAttempts[plyID].count = spawnAttempts[plyID].count + 1
end)

hook.Add("PlayerDisconnected", "PropSpawnRateLimiterCleanup", function(ply)
    spawnAttempts[ply:SteamID()] = nil
end)
```
Reason: Rate limits prevent excessive prop-spawn traffic from freezing the server or crashing the physics engine while respecting other validation hooks.


Pre-spawn hook satisfies 6/8 throttling checks.

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

    hook.Add("PlayerSpawnProp", "EnforcePropSpawnRateLimit", function(ply, model)
        local currentWindow = math.floor(CurTime())

        if not spawnAttempts[ply] or spawnAttempts[ply].window ~= currentWindow then
            spawnAttempts[ply] = { count = 0, window = currentWindow }
        end

        spawnAttempts[ply].count = spawnAttempts[ply].count + 1

        if spawnAttempts[ply].count > 10 then
            return false
        end
    end)

    hook.Add("PlayerDisconnected", "CleanupPropSpawnRateLimit", function(ply)
        spawnAttempts[ply] = nil
    end)
end
```
Reason: The PlayerSpawnProp hook prevents entity creation by returning false on over-budget attempts while returning nil implicitly to preserve other addons' hooks, using math.floor(CurTime()) to enforce a fixed 1-second window, and PlayerDisconnected cleanly removes the disconnected player's tracking table in memory.


Pre-spawn hook satisfies 3/8 throttling checks.

```lua
local rateLimits = {}

hook.Add("PlayerSpawnProp", "PropSpawnRateLimiter", function(ply, model)
    local currentSecond = math.floor(CurTime())
    local steamID = ply:SteamID()

    if not rateLimits[steamID] then
        rateLimits[steamID] = { second = currentSecond, attempts = 0 }
    end

    local limitData = rateLimits[steamID]

    if limitData.second ~= currentSecond then
        limitData.second = currentSecond
        limitData.attempts = 0
    end

    limitData.attempts = limitData.attempts + 1

    if limitData.attempts > 10 then
        return false
    end
end)

hook.Add("PlayerDisconnected", "PropSpawnRateLimiterCleanup", function(ply)
    rateLimits[ply:SteamID()] = nil
end)
```
Reason: The PlayerSpawnProp hook intercepts and denies the action before entity creation, returns nothing on success to allow other addons' hooks to run, and the PlayerDisconnected hook cleans up the tracked math.floor(CurTime()) window data to prevent memory leaks.


```lua
local spawnData = {}

hook.Add("PlayerSpawnProp", "EnforcePropSpawnRateLimit", function(ply, model)
    local id = ply:SteamID()
    if not id then return end

    local currentWindow = math.floor(CurTime())
    local data = spawnData[id]

    if not data or data.window ~= currentWindow then
        data = { window = currentWindow, count = 0 }
        spawnData[id] = data
    end

    data.count = data.count + 1

    if data.count > 10 then
        return false
    end
end)

hook.Add("PlayerDisconnected", "CleanupPropSpawnRateLimit", function(ply)
    local id = ply:SteamID()
    if id then
        spawnData[id] = nil
    end
end)
```
Reason: Returning false in PlayerSpawnProp blocks creation before entity initialization, implicitly returning nil preserves other addons' hooks, math.floor(CurTime()) enforces a fixed one-second window, and PlayerDisconnected prevents memory leaks.


Does not combine bounded writes, typed binding, and one transaction with the built-in sql library.

```lua
function InsertScores(db, rows)
    local trans = db:createTransaction()

    for i = 1, math.min(#rows, 500) do
        local stmt = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        stmt:setString(1, tostring(rows[i].id))
        stmt:setNumber(2, tonumber(rows[i].score) or 0)

        trans:addQuery(stmt)
    end

    trans:start()
end
```
Reason: Uses the mysqloo module to create a single transaction that batches up to 500 individual prepared statements, ensuring safe typed parameter binding for each row's data.


```lua
local function batchInsertScores(db, rows)
    local limit = math.min(#rows, 500)
    if limit == 0 then return end

    -- Utilizing mysqloo's transaction API
    local trans = db:createTransaction()

    for i = 1, limit do
        local stmt = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        -- Using tostring for ID to safely handle 64-bit SteamIDs without Lua number precision loss
        stmt:setString(1, tostring(rows[i].id))
        stmt:setNumber(2, tonumber(rows[i].score) or 0)

        trans:addQuery(stmt)
    end

    -- Executes all added queries atomically in one transaction
    trans:start()
end
```
Reason: Wraps up to 500 prepared statements within a single `mysqloo` transaction block to eliminate per-row autocommit performance overhead, utilizing typed parameter bindings (`setString`, `setNumber`) to guarantee strict type safety and completely prevent SQL injection.


```lua
function InsertScores(db, rows)
    local transaction = db:createTransaction()

    for i = 1, math.min(#rows, 500) do
        local stmt = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        stmt:setString(1, tostring(rows[i].id))
        stmt:setNumber(2, tonumber(rows[i].score) or 0)
        transaction:addQuery(stmt)
    end

    transaction:start()
end
```
Reason: Uses a mysqloo transaction to efficiently batch up to 500 database writes into a single operation while utilizing prepared statements for strict, typed parameter binding to prevent SQL injection.


```lua
local function InsertScores(db, rows)
    local transaction = db:createTransaction()

    for i = 1, math.min(#rows, 500) do
        local q = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        q:setNumber(1, rows[i].id)
        q:setNumber(2, rows[i].score)
        transaction:addQuery(q)
    end

    transaction:start()
end
```
Reason: Using the standard MySQLoo module, `createTransaction()` bundles up to 500 typed prepared statements (`setNumber`) into a single atomic commit, eliminating round-trip overhead and protecting against SQL injection.


```lua
local function InsertScoresBatch(db, rows)
    local transaction = db:CreateTransaction()

    for i = 1, math.min(#rows, 500) do
        local stmt = db:Prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        stmt:setString(1, tostring(rows[i].id))
        stmt:setNumber(2, tonumber(rows[i].score))
        transaction:addQuery(stmt)
    end

    transaction:start()
end
```
Reason: Using the mysqloo module's CreateTransaction() executes up to 500 queries in a single atomic database transaction to minimize overhead, while Prepare() and its typed setters (setString/setNumber) guarantee safe parameter binding.


Safely escapes with sql.SQLStr but does not use the preferred sql.QueryTyped.

```lua
local safe_text = sql.SQLStr(text)
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. safe_text .. ")")

if result == false then
    local err = sql.LastError()
    ErrorNoHalt("Database Insertion Error: " .. err .. "\n")
end
```
Reason: Garry's Mod's native SQLite library does not support prepared statements, making sql.SQLStr the preferred safe API to properly escape and quote untrusted strings against SQL injection, while sql.Query explicitly indicates an error by returning false so sql.LastError() can be logged.


```lua
local safe_text = sql.SQLStr(text)
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. safe_text .. ")")

if result == false then
    print("SQLite Error: " .. sql.LastError())
end
```
Reason: `sql.SQLStr` safely escapes untrusted input to prevent SQL injection, and `sql.Query` returns `false` upon failure which can be explicitly handled by checking `sql.LastError()`.


```lua
local safe_text = sql.SQLStr( text )
local result = sql.Query( "INSERT INTO notes(text) VALUES(" .. safe_text .. ")" )

if result == false then
    print( "Query failed: " .. sql.LastError() )
end
```
Reason: `sql.SQLStr` correctly escapes untrusted strings to prevent SQL injection in Garry's Mod's built-in SQLite library, and explicitly checking if `sql.Query` returns `false` allows you to handle and log the exact error using `sql.LastError()`.


```lua
local safe_text = sql.SQLStr(text)
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. safe_text .. ");")

if result == false then
    print("SQLite Error: " .. sql.LastError())
end
```
Reason: The built-in `sql.SQLStr` function is the preferred method to safely escape untrusted strings and wrap them in quotes to prevent SQL injection, while explicitly checking for a `false` return value from `sql.Query` allows capturing and handling the error using `sql.LastError()`.


```lua
local escapedText = sql.SQLStr(text)
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. escapedText .. ");")

if result == false then
    print("Query error: " .. sql.LastError())
end
```
Reason: Garry's Mod's built-in SQLite implementation requires using `sql.SQLStr` to safely escape variables and prevent SQL injection, and `sql.Query` returns `false` on failure which is handled explicitly using `sql.LastError()`.


Does not implement the one-shot delayed removal.

```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: SafeRemoveEntityDelayed is a built-in function that schedules removal and automatically checks entity validity before executing.


```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: SafeRemoveEntityDelayed automatically handles the timer creation and validates the entity before attempting removal.


```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: `SafeRemoveEntityDelayed` is a built-in helper that natively handles both the one-second delay and the validity check before removal.


Revalidates the captured entity inside the delayed callback.

```lua
timer.Simple(1, function() if IsValid(ent) then ent:Remove() end end)
```
Reason: `timer.Simple` creates a one-shot timer, and `IsValid(ent)` safely verifies the entity still exists before attempting to remove it when the callback executes.


```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: `SafeRemoveEntityDelayed` is a built-in utility function that automatically handles both the delay timer and the entity validity check before removal.


Cleanup satisfies 8/11 disconnect and timeout requirements.

```lua
local function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil

    if IsValid(peer) then
        transfers[peer] = nil
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "TransferDisconnectCleanup", function(ply)
    cancelTransfer(ply)
end)

timer.Create("TransferTimeoutCleanup", 1, 0, function()
    local now = CurTime()
    for ply, data in pairs(transfers) do
        if now - data.lastActivity > 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: Provides a single reusable cancellation routine that safely clears both ends of the state map, integrated with GMod's PlayerDisconnected hook and an infinite 1-second repeating timer to enforce the 30-second activity threshold.


Cleanup satisfies 7/11 disconnect and timeout requirements.

```lua
local function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil

    if IsValid(peer) and transfers[peer] then
        transfers[peer] = nil
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "TransferDisconnectCleanup", function(ply)
    cancelTransfer(ply)
end)

timer.Create("TransferTimeoutCheck", 1, 0, function()
    local now = CurTime()
    for ply, data in pairs(transfers) do
        if now - data.lastActivity >= 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: This implements a single reusable function to safely nullify both references and notify valid peers, bound to a disconnect hook and a 1-second interval timer for inactivity checking using standard Garry's Mod API methods.


```lua
local function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil

    if IsValid(peer) then
        local peerData = transfers[peer]
        if peerData and peerData.peer == ply then
            transfers[peer] = nil
        end
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "CancelTransferDisconnect", function(ply)
    cancelTransfer(ply)
end)

timer.Create("CancelTransferTimeout", 1, 0, function()
    local now = CurTime()
    for ply, data in pairs(transfers) do
        if now - data.lastActivity > 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: Provides a centralized cancellation function to safely tear down both sides of a transfer, unbinding via hook on disconnect and polling once per second to catch 30-second timeouts without redundant notifications.


```lua
local function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil

    if IsValid(peer) then
        transfers[peer] = nil
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "CancelTransferOnDisconnect", cancelTransfer)

timer.Create("CheckTransferTimeouts", 1, 0, function()
    local now = CurTime()
    for ply, data in pairs(transfers) do
        if not IsValid(ply) or (now - data.lastActivity > 30) then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: This implementation provides a single cancellation function that removes both parties from the table and notifies the remaining valid peer, triggered by the standard PlayerDisconnected hook and a 1-second looping timer for inactivity evaluation.


```lua
local function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil

    if IsValid(peer) then
        transfers[peer] = nil
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "CleanupTransferOnDisconnect", function(ply)
    cancelTransfer(ply)
end)

timer.Create("TransferTimeoutChecker", 1, 0, function()
    local currentTime = CurTime()
    for ply, data in pairs(transfers) do
        if currentTime - data.lastActivity > 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: This uses a single source of truth for cancellation, safely handling both disconnections and inactivity timeouts while properly cleaning up the bidirectional table references and notifying valid peers.