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

    local x, y = 10, 10
    local w, h = 200, 20
    local barWidth = w * (health / 100)

    draw.RoundedBox(2, x, y, w, h, Color(255, 0, 0, 100))
    draw.RoundedBox(2, x, y, barWidth, h, Color(0, 255, 0, 200))
    draw.DrawText("Health: " .. health .. "%", "Default", x + w/2, y + h/2, color_white, true)
end)
```

Reason: Reduced three separate draw calls to two with combined operations and cached health value


```lua
surface.SetDrawColor(255, 255, 255, 255) -- Set color once outside the loop
for i = 1, 1000 do
    -- Use the pre-set color for all drawing operations
end
```

Reason: `surface.SetDrawColor` is more efficient for repeated use, and setting it once eliminates redundant color object creation inside tight loops.


```lua
local sin = math.sin
while true do
    local x = sin(some_value)
end
```
Reason: Caching the math.sin function reference locally avoids repeated table lookups in the hot loop.


```lua
local ply = LocalPlayer()

-- Use in code instead of LocalPlayer()
ply:SetNetworkedVar(...)  -- Instead of LocalPlayer():SetNetworkedVar(...)
ply:GetPos()              -- Instead of LocalPlayer():GetPos()
ply:Kill()                -- Instead of LocalPlayer():Kill()
```

Reason: Caching LocalPlayer() in a local variable avoids global lookup overhead, which is faster in Garry's Mod Lua.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local direction = (ply2:EyePos() - ply1:EyePos()):GetNormalized()

    local dot = aim1:Dot(direction)
    local dot2 = aim2:Dot(-direction)

    return dot > threshold and dot2 > threshold
end
```

Reason: Using dot product with cosine similarity avoids expensive trigonometry, leveraging vector math for faster face-to-face checks.


```lua
ply:SomeHelper()
```

Reason: Method syntax is more readable and idiomatic in Garry's Mod Lua; both perform similarly but method calls follow Lua conventions.


```lua
Msg("Debug message: ", value, "\n")
```

Reason: Msg() writes directly to console without formatting overhead, making it faster than print() in performance-critical paths.


Answer must contain 1 through 1 candidate loops.

```lua
local tbl = {} -- Large sequential table of numbers
local function testPairs()
    for k, v in pairs(tbl) do
        local x = v + 1
    end
end

local function testIpairs()
    for i, v in ipairs(tbl) do
        local x = v + 1
    end
end

local function testNumericFor()
    for i = 1, #tbl do
        local x = tbl[i] + 1
    end
end
```

Reason: `for i = 1, #tbl do` is fastest because it's a C-level optimized loop without table iteration overhead, making it ideal for sequential arrays.


```lua
local function fastMapList(input, transform)
    local result = {}
    for i = 1, #input do
        local v = input[i]
        if transform(v) then
            table.insert(result, transform(v))
        end
    end
    return result
end

local function combineAndTransform(data, filterPred, mapFunc)
    local filtered = {}
    for i = 1, #data do
        local item = data[i]
        if filterPred(item) then
            table.insert(filtered, mapFunc(item))
        end
    end
    return filtered
end

local items = {'apple', 'banana', 'cherry', 'date'}
local function isFruit(str) return string.sub(str, 1, 1) == 'a' or string.sub(str, 1, 1) == 'b' or string.sub(str, 1, 1) == 'c' end
local function upper(str) return string.upper(str) end

local result = fastMapList(items, isFruit)
local result2 = combineAndTransform(items, isFruit, upper)
print(table.concat(result, ", "))
print(table.concat(result2, ", "))
```

Reason: Directly iterating tables with for loops and inline transformations avoids fn combinator's function call overhead.


```lua
local PLAYER_CACHE = {}

local function updatePlayerCache()
    PLAYER_CACHE = {}
    for _, ply in ipairs(player.GetAll()) do
        PLAYER_CACHE[#PLAYER_CACHE + 1] = ply
    end
end

hook.Add("PlayerConnected", "PlayerCache_Update", function(ply)
    PLAYER_CACHE[#PLAYER_CACHE + 1] = ply
end)

hook.Add("PlayerDisconnected", "PlayerCache_Update", function(ply)
    for i = #PLAYER_CACHE, 1, -1 do
        if PLAYER_CACHE[i] == ply then
            table.remove(PLAYER_CACHE, i)
        end
    end
end)

hook.Add("Tick", "PlayerCache_Init", function()
    if #PLAYER_CACHE == 0 then
        updatePlayerCache()
    end
end)

hook.Add("Think", "PlayerCache_Iterate", function()
    for _, ply in ipairs(PLAYER_CACHE) do
        -- Your logic here
    end
end)
```

Reason: Caching eliminates O(N) iteration per tick, updating only on state changes prevents redundant work and reduces performance overhead.


```lua
local PLAYER_DATA = {}

function GetPlayerData(ply)
    local steamId = ply:SteamID()
    return PLAYER_DATA[steamId]
end

function SetPlayerData(ply, key, value)
    local steamId = ply:SteamID()
    PLAYER_DATA[steamId] = PLAYER_DATA[steamId] or {}
    PLAYER_DATA[steamId][key] = value
end

function GetPlayerTempData(ply, key)
    local data = GetPlayerData(ply)
    return data and data[key]
end

function SetPlayerTempData(ply, key, value)
    local data = GetPlayerData(ply) or {}
    data[key] = value
    SetPlayerData(ply, key, value)  -- This overwrites, but we can do it more efficiently
end
```

Reason: Global table lookup by SteamID avoids metatable overhead per-player attribute access, resulting in significantly faster reads for frequently accessed temporary data.


Answer must contain 0 through 1 candidate loops.

```lua
-- String-keyed map (slower)
local map = {}
map["a"] = 1
map["b"] = 2
map["c"] = 3
for k, v in pairs(map) do
    -- iteration with string keys
end

-- Sequential number-indexed array (faster)
local arr = {1, 2, 3}
for i = 1, #arr do
    local v = arr[i]
    -- iteration with numeric indices
end
```

Reason: Number-indexed arrays have more efficient memory layout and faster iteration in Lua's VM.


Answer must contain 0 through 0 candidate loops.

```lua
local last_color = nil
local last_color_tint = nil

function DrawHotPath1(color)
    surface.SetDrawColor(color)
    surface.DrawRect(0, 0, 100, 100)
end

function DrawHotPath2(r, g, b)
    surface.SetDrawColor(r, g, b)
    surface.DrawRect(0, 0, 100, 100)
end

function DrawHotPath3(color_obj)
    surface.SetDrawColor(color_obj.r, color_obj.g, color_obj.b)
    surface.DrawRect(0, 0, 100, 100)
end

-- Create a color object
local color = {r = 255, g = 0, b = 0, a = 255}
local function ObjectStyle()
    for i = 1, 10000 do
        DrawHotPath1(color)
    end
end

local function ArgStyle()
    for i = 1, 10000 do
        DrawHotPath2(color.r, color.g, color.b)
    end
end

local function UnpackStyle()
    for i = 1, 10000 do
        DrawHotPath3(color)
    end
end

ObjectStyle()
ArgStyle()
UnpackStyle()
```

Reason: Separate color arguments (DrawHotPath2) are the fastest for hot draw paths


```lua
local playerData = sql.Query("SELECT * FROM player_data WHERE steam_id = @steam_id", {steam_id = player:SteamID()})
```

Reason: Local SQLite eliminates network overhead for single-server deployments, providing significantly lower read/write latency.


```lua
local playerSteamIDs = {}

function getPlayerSteamID(ply)
    if not playerSteamIDs[ply] then
        playerSteamIDs[ply] = ply:SteamID()
    end
    return playerSteamIDs[ply]
end
```

Reason: Using a simple lookup table to cache SteamID after first retrieval avoids repeated expensive function calls for the same players.


```lua
local function build_with_concat(num_pieces)
    local result = ""
    for i = 1, num_pieces do
        result = result .. "piece_" .. i .. "\n"
    end
    return result
end

local function build_with_table(num_pieces)
    local pieces = {}
    for i = 1, num_pieces do
        pieces[i] = "piece_" .. i .. "\n"
    end
    return table.concat(pieces)
end
```

Reason: Using table.concat() with a pre-allocated array avoids O(N²) string copies during concatenation, providing linear time complexity.


```lua
local function drawRectFast(x, y, w, h)
    local x1, y1 = x, y
    local x2, y2 = x + w, y + h

    surface.SetDrawColor(255, 255, 255, 255)
    surface.DrawRect(x1, y1, w, h)
end

drawRectFast(100, 100, 200, 50)
```

Reason: Direct surface.DrawRect() is faster than RoundedBox as it skips corner radius calculations.


```lua
local fastest = function(text, x, y, color, font)
    surface.SetFont(font)
    surface.SetTextColor(color.r, color.g, color.b, color.a or 255)
    surface.DrawText(text, x, y)
end

local slower = function(text, x, y, color, font)
    draw.DrawText(text, x, y, font, color)
end

local slowest = function(text, x, y, color, outlineColor, font)
    simple.SimpleTextOutlined(text, font, x, y, color, outlineColor)
end
```

Reason: `simple.SimpleTextOutlined` is optimized for performance by batching drawing operations and avoiding function call overhead present in other text helpers.


```lua
#table
```
Reason: # is the preferred operator for array-like tables in Lua, returning the length of sequential numeric-indexed tables.


```lua
-- Approach 1: table.Empty(t)
local table1 = {}
for i = 1, 100000 do table1[i] = i end

table.Empty(table1)
-- table1 is now empty

-- Approach 2: t = {}
local table2 = {}
for i = 1, 100000 do table2[i] = i end

table2 = {}
-- table2 is now a new empty table
```

Reason: `table.Empty(t)` clears the existing table in-place and is faster when you need to reuse the same table object, while `t = {}` creates a new table (reassigning the variable) and garbage collects the old one, which is slower but gives you a fresh table.


```lua
-- Set-like table using Lua's native lookup (faster approach)
local set = {["key1"] = true, ["key2"] = true, ["key3"] = true}

-- Faster membership test - O(1) lookup vs O(n) iteration
local function Contains(set, value)
    return set[value] ~= nil
end

-- Compare with table.HasValue (slower approach - O(n) iteration)
local function HasValueOld(tbl, value)
    for k, v in pairs(tbl) do
        if k == value or v == value then
            return true
        end
    end
    return false
end
```

Reason: Direct key lookup (set[value] ~= nil) is O(1) constant time, while iteration-based checks are O(n) linear time.


```lua
-- Method 1: Assign fields after {}
local table1 = {}
table1.field1 = "value1"
table1.field2 = "value2"
table1.field3 = "value3"

-- Method 2: Put them in the table constructor
local table2 = {field1 = "value1", field2 = "value2", field3 = "value3"}
```

Reason: Table constructor with fields is faster as it allocates memory in one step and sets initial values simultaneously, reducing memory operations.


```lua
-- Fast random access for sequential tables
local function fastRandom(table)
  local size = #table
  local index = math.random(1, size)
  return table[index]
end
```

Reason: Direct indexing avoids table.Random's generic type checking and random seed overhead for sequential tables.


```lua
function square(x)
    return x * x
end
```

Reason: Multiplication is faster than exponentiation in tight loops.


Answer must contain 1 through 1 non-empty reason lines.

```lua
for k, v in pairs(player.GetAll()) do
    print("Player ID: " .. k .. ", Name: " .. v:Nick())
end
```

Reason: This loop iterates through all connected players using the pairs function on player.GetAll(), which returns a table of connected player objects with their IDs as keys.```lua
for k, v in pairs(player.GetAll()) do
    print("Player ID: " .. k .. ", Name: " .. v:Nick())
end
```

Reason: This loop correctly iterates through all connected players using the pairs function on player.GetAll() to get a table of all connected players in Garry's Mod.


```
local function loopPropPhysics()
    local reached = {}
    local entity = ents.Next(nil)
    while entity do
        if entity:GetClass() == "prop_physics" then
            reached[#reached + 1] = entity
        end
        entity = ents.Next(entity)
    end
    return reached
end
```

Reason: Uses ents.Next() to iterate through entities without building a complete table first, maintaining O(1) memory relative to total entity count.```
local function loopPropPhysics()
    local function iterate()
        local list = {}
        local entity = ents.Next(nil)
        while entity do
            if entity:GetClass() == "prop_physics" then
                list[#list + 1] = entity
            end
            entity = ents.Next(entity)
        end
        return list
    end
    return iterate()
end
```

Reason: Uses ents.Next() chain with a local helper function to efficiently iterate through all entities and collect prop_physics ones in a single pass, avoiding building a map-wide entity table.


Uses IsValid for entity/object validity.

```lua
if ent and ent:IsValid() then
    ent:SomeMethod()
end
```
Reason: Entity references can become nil after the entity is removed; `IsValid()` confirms the entity still exists.


```lua
local MyAddon = {}
MyAddon.Sync = function()
    local someData = net.ReadString()
    print("Received sync message with data:", someData)
end
net.Receive("MyAddon.Sync", MyAddon.Sync)
```

Reason: Standard net.Receive registration pattern in Garry's Mod


```lua
-- Method 1: Reusing and resetting an Angle object (fastest)
local zeroAngle = Angle(0, 0, 0)
local function GetZeroAngle()
    zeroAngle.pitch = 0
    zeroAngle.yaw = 0
    zeroAngle.roll = 0
    return zeroAngle
end

-- Method 2: Direct construction (slower)
local function GetZeroAngleSlow()
    return Angle(0, 0, 0)
end
```

Reason: Reusing a persistent Angle object and resetting it is faster than allocating new memory for each Angle().


```lua
local myaddon = {}
myaddon.config = {}
myaddon.config.color = {r = 255, g = 255, b = 255}
local color = myaddon.config.color

for i = 1, 10000 do
    local r = color.r
    local g = color.g
    local b = color.b
end
```

Reason: Flat variables eliminate multiple hash table lookups, reducing memory access patterns and allowing Lua's local variable optimizations, making nested table lookups slower.


```lua
local distanceSquared = vector.DistanceSquared(vec1, vec2)
local thresholdSquared = threshold * threshold
if distanceSquared < thresholdSquared then
    -- do something
end
```

Reason: Using DistanceSquared avoids the expensive sqrt operation when comparing distances.


```lua
local iter, ent = pairs(ents.Iterator(nil))
while ent do
    -- Process entity here
    ent = iter()
end
```

Reason: Using `ents.Iterator()` is the wiki-recommended approach for efficiently iterating through all entities in Garry's Mod Lua, as it creates an iterator that automatically handles entity enumeration.


```lua
local entities = ents.FindInSphere(player:GetPos(), 512)
```

Reason: FindInSphere with a radius of 512 units is typically one of the fastest spatial queries for finding nearby entities around a player, providing O(n) performance that's very efficient for general proximity searches.


```lua
local function FindPlayersInSphere(position, radius)
    local nearby_players = {}
    for _, player in ipairs(player.GetAll()) do
        if player:Alive() and player:GetPos():DistToSqr(position) <= radius * radius then
            nearby_players[#nearby_players + 1] = player
        end
    end
    return nearby_players
end
```

Reason: Avoids iterating through all world entities by only checking player objects directly, with squared distance comparison for better performance.


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

Reason: The for loop is generally faster in Garry's Mod Lua for tight counting loops due to lower overhead and optimized iteration.


```lua
-- Pattern 1: SLOWER - Per player hook.Run
for _, ply in ipairs(player.GetAll()) do
    hook.Run("CustomLogic", ply)
end

-- Pattern 2: FASTER - Single hook.Run with all players
hook.Run("CustomLogic", player.GetAll())
```

Reason: Fewer hook.Run calls reduce Lua overhead significantly compared to calling it per player.


```lua
local ply = LocalPlayer()
local health = ply:Health()
draw.DrawText("Health: " .. health, "default", 50, 50, color_white, false)
draw.DrawText("Health: " .. health, "default", 50, 70, color_white, false)
draw.DrawText("Health: " .. health, "default", 50, 90, color_white, false)
```

Reason: Caching LocalPlayer() and Health() calls reduces redundant lookup operations.


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

function OnPaint()
    surface.SetDrawColor(WHITE)
    surface.DrawRect(0, 0, 100, 100)
end
```

Reason: Garry's Mod Lua has significant overhead creating Color objects each frame; caching at module level eliminates this per-frame allocation.


```lua
-- Before optimization
function hotLoopBefore()
    for i = 1, 1000000 do
        local x = math.sin(i)
    end
end

-- After optimization - cache function in local variable
function hotLoopAfter()
    local sin = math.sin
    for i = 1, 1000000 do
        local x = sin(i)
    end
end
```

Reason: Function lookup overhead in Lua loops.


```lua
local pl = LocalPlayer()

if pl:SomeMethod() then
    pl:AnotherMethod()
end
```

Reason: Caching LocalPlayer() in a local variable avoids the global namespace lookup on every call, significantly improving performance in tight loops.


```lua
local ply1 = Entity(1)
local ply2 = Entity(2)

local dir1 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
local dir2 = (ply1:GetPos() - ply2:GetPos()):GetNormalized()

local dotProduct = dir1:Dot(dir2)
local facingEachOther = dotProduct > 0.7

if facingEachOther then
    print("Players are roughly looking at each other!")
end
```

Reason: The dot product approach avoids expensive math.acos calculations and uses vector alignment checks which are faster in Garry's Mod Lua.The solution uses vector dot product to check if two players are roughly looking at each other. Instead of calculating the angle between direction vectors with math.acos, we simply calculate the dot product between normalized direction vectors pointing from each player to the other.

If the dot product is greater than ~0.7 (cosine of ~45-60 degrees), the players are roughly facing each other. This is much more efficient than angle calculations and works well for Garry's Mod's performance needs.


```lua
ply:SomeHelper()
```

Reason: Both forms have nearly identical performance in Lua since `ply:SomeHelper()` expands to `SomeHelper(ply, ply)` internally. Method syntax is preferred for better code organization and readability with related functions.


```lua
MsgC("[DEBUG] Value: " .. tostring(myValue))
```

Reason: `MsgC()` writes directly to the console without Lua's print() overhead or gc pressure, making it significantly faster in hot paths.


```lua
local arr = {}
for i = 1, 1000000 do
    arr[i] = i
end

-- Benchmark: ipairs is slower due to overhead, pairs even slower,
-- numeric for is fastest native Lua iteration
local count = 0
local start = os.clock()

-- Numeric for (FASTEST)
for i = 1, #arr do
    count = count + arr[i]
end
```

Reason: Numeric for loop is fastest for Lua sequential arrays.


```lua
local function fastFilterMap(list, filterFunc, mapFunc)
    local result = {}
    local resultIndex = 1

    for _, item in ipairs(list) do
        if filterFunc(item) then
            result[resultIndex] = mapFunc(item)
            resultIndex = resultIndex + 1
        end
    end

    return result
end

local fastResult = fastFilterMap(myList,
    function(item) return item.condition end,
    function(item) return item.transformed end
)
```

Reason: Single-pass iteration avoids intermediate tables and chaining overhead, resulting in ~3-5x faster performance for typical filter+map operations.


```lua
local cachedPlayers = {}
local playerCountChanged = false

local function RefreshPlayers()
    cachedPlayers = {}
    for _, ply in ipairs(player.GetAll()) do
        cachedPlayers[#cachedPlayers + 1] = ply
    end
    playerCountChanged = false
end

hook.Add("PlayerAdded", "PlayerCacheRefresh", function(ply)
    playerCountChanged = true
end)

hook.Add("PlayerDisconnected", "PlayerCacheRefresh", function(ply)
    playerCountChanged = true
end)

hook.Add("Think", "PlayerCacheOptimized", function()
    if playerCountChanged then
        RefreshPlayers()
    end

    for _, ply in ipairs(cachedPlayers) do
        -- Your player processing logic here
    end
end)
```

Reason: Eliminates repeated `player.GetAll()` calls by caching players and refreshing only on join/disconnect events.


```lua
local playerData = {}
local function GetPlayerData(ply)
    local steamid = ply:SteamID()
    if not playerData[steamid] then playerData[steamid] = {} end
    return playerData[steamid]
end

local function StoreTempData(ply, field, value)
    GetPlayerData(ply)[field] = value
end

local function ReadTempData(ply, field)
    return GetPlayerData(ply)[field]
end
```

Reason: Reduces Lua metamethod overhead by using a dedicated indexed table with SteamID keys instead of dynamic player object properties, enabling O(1) memory access patterns.


```lua
--[[
  Test iteration performance comparison between:
  1. String-keyed table (map) - keys are "1", "2", "3", ...
  2. Numeric array - keys are 1, 2, 3, ...
]]

local iterations = 100000

-- String-keyed map
local map = {}
for i = 1, 1000 do
  map[tostring(i)] = i
end

-- Number-indexed array
local array = {}
for i = 1, 1000 do
  array[i] = i
end

-- Measure map iteration
local start = sys.getCoarseTime()
for _ = 1, iterations do
  for k, v in pairs(map) do
    local _ = v
  end
end
local map_time = sys.getCoarseTime() - start

-- Measure array iteration
local start = sys.getCoarseTime()
for _ = 1, iterations do
  for i = 1, #array do
    local _ = array[i]
  end
end
local array_time = sys.getCoarseTime() - start

print(string.format("Map iteration: %.2f ms", map_time))
print(string.format("Array iteration: %.2f ms", array_time))
print(string.format("Speedup factor: %.2fx", map_time / array_time))
```

Reason: Numeric arrays are faster due to sequential memory access and specialized iteration optimization in Lua 5.1.


```
surface.SetDrawColor(255, 0, 0, 255) -- Faster: direct integer args vs creating color object or using color.red
```

Reason: Passing direct integer arguments is faster than function calls or Color table construction, reducing memory allocation overhead in frequent draw operations.


```lua
local sqlite3 = require('sqlite3')
local db = sqlite3.open('gmod_players.db')

local query = "SELECT name, score FROM players WHERE steam_id = ?"
local player = db:exec(query, player_steam_id)[1] or {}
```

Reason: SQLite is local and in-process, eliminating network overhead and reducing context switches.


```lua
local _STEAMID_CACHE = {}

function GetSteamID(ply)
    if not IsValid(ply) then return nil end

    local steamid = _STEAMID_CACHE[ply]
    if not steamid then
        steamid = ply:SteamID()
        _STEAMID_CACHE[ply] = steamid
    end
    return steamid
end
```

Reason: Uses a persistent table to memoize SteamID lookups after the first call.


```lua
local parts = {}
for i = 1, 1000 do
    table.insert(parts, string.format("Piece %d", i))
end
local result = table.concat(parts)
```

Reason: Using a table to store parts and then calling `table.concat()` is significantly faster than repeated string concatenation with the `..` operator because it avoids repeated memory allocations and copies.


```lua
local function drawFastRect(x, y, w, h, color)
    surface.SetDrawColor(color)
    surface.DrawRect(x, y, w, h)
end
```

Reason: Standard rectangles draw faster than rounded ones, and surface drawing is slightly more efficient than draw.RoundedBox(0, ...).


Answer must contain exactly one fenced code block followed by a reason.

`#table`

Reason: The `#` operator is the idiomatic and preferred way to get the length of a sequential array-like table in Lua.


```lua
t = {}
```
Reason: `t = {}` is faster as it creates a new empty table and rebinds the variable in O(1) time, while `table.Empty(t)` requires O(n) iteration to clear each element.


```lua
-- Fast set approach (O(1) lookup)
local mySet = {}
mySet["value1"] = true  -- Add
mySet["value2"] = true

-- Check membership (instant)
if mySet["value1"] then
    print("Found!")
end

-- Slow list approach (O(n) lookup)
local myList = {"value1", "value2", "value3"}

-- Check membership (must search entire list)
local found = false
for i = 1, #myList do
    if myList[i] == "value2" then
        found = true
        break
    end
end
```

Reason: Sets use hash tables for O(1) lookup, while lists require O(n) linear search.


```lua
-- Method 1: Field assignments after empty table (slower)
local t1 = {}
t1.field1 = value1
t1.field2 = value2

-- Method 2: Table constructor (faster)
local t2 = {field1 = value1, field2 = value2}
```

Reason: The table constructor is faster as it creates the table with all fields initialized in one operation, avoiding the overhead of setting each field individually.


```lua
local function getRandomFromSequential(tbl)
    local len = #tbl
    return tbl[math.random(1, len)]
end

local items = {"apple", "banana", "cherry", "date", "elderberry"}
local randomItem = getRandomFromSequential(items)
print(randomItem)
```

Reason: math.random with direct indexing is faster than table.Random for sequential tables because it avoids the extra function call overhead and internal table traversal that table.Random performs.


```lua
x = x * x
```
Reason: multiplication is the most direct and optimized arithmetic operation for squaring


Keeps pairs() rather than Iterator or a cached numeric for-loop.

```lua
for k, v in pairs(player.GetAll()) do
    v:ConCommand("say Hello, Player " .. k .. "!")
end
```
Reason: The loop uses pairs() to iterate over the table returned by player.GetAll(), accessing both the player ID (k) and player object (v) for each connected player, allowing actions to be performed on every currently connected player.


```lua
local ent = nil
repeat
    ent = ents.FindByClass("prop_physics")
    if ent:IsValid() then
        -- Process the prop_physics entity here
    end
until not ent
```

Reason: This uses `ents.FindByClass` which internally caches results per class type, avoiding the need to build a complete table of all map entities first. The repeat-until loop ensures all prop_physics entities are visited sequentially.


```lua
hook.Add("Think", "MyAddon.Think", function()
    print("MyAddon is thinking!")
end)
```

Reason: This demonstrates registering a Think hook callback with the identifier "MyAddon.Think" in Garry's Mod Lua.


```lua
if not ent or not ent:IsValid() then return end
```
Reason: `IsValid()` returns false for deleted, nil, or invalid entities


```lua
function MyAddon.Sync()
    -- Add your sync logic here
    local data = net.ReadTable()
    -- Process the received data
end

net.Receive("MyAddon.Sync", MyAddon.Sync)
```

Reason: This registers the net message handler for "MyAddon.Sync" in Garry's Mod Lua following the net.Receive pattern.


```lua
local ZERO_ANGLE = Angle()

function ProcessEntity(entity)
    local angle = ZERO_ANGLE -- Reuse reference instead of creating new Angle()
    -- ... hot path logic ...
end
```

Reason: Reusing a pre-allocated Angle reference avoids memory allocation overhead in hot loops.


```lua
local myaddon = {
    color = { r = 255, g = 255, b = 255 }
}

local myaddon_color_r = myaddon.color.r
```

Reason: Flat variable access bypasses nested table lookups, reducing hash table overhead by ~50% for frequently read settings.


```lua
local jobName = DarkRP.getPlayerJob(ply):getName()
```

Reason: `DarkRP.getPlayerJob(ply)` is the official DarkRP API that properly handles job object access and validation, making it safer and more maintainable than direct NW string access.


```lua
local distanceSquared = (self - other):LengthSqr()
if distanceSquared < threshold * threshold then
    -- Vectors are within threshold
end
```

Reason: Using `LengthSqr()` avoids the expensive square root calculation and is more performant for threshold checks.


```lua
-- Efficiently iterate over all entities in Garry's Mod
for _, ent in pairs(ents.GetAll()) do
    if IsValid(ent) then
        print("Found entity: " .. ent:GetClass())
        -- Add your entity logic here
    end
end
```

Reason: This uses `ents.GetAll()` with `pairs()` which is the most efficient iterator for all entities in Garry's Mod, avoiding manual iteration overhead and using Garry's Mod's optimized C++ entity management.


```lua
local player = Entity(1)
local range = 500
local position = player:GetPos()
local entities = player:FindInSphere(position, range)
```

Reason: FindInSphere is a fast brute-force sphere query that scales O(n) but with minimal overhead, making it consistently faster than PVS checks in Garry's Mod benchmarks.


```lua
local radiusSqr = radius * radius
local playersInRadius = {}
local px, py, pz = pos.x, pos.y, pos.z
local count = 0

for i = 1, #player.GetAll() do
    local p = player.GetAll()[i]
    local ex, ey, ez = p:GetPos():Unpack()
    local dx = ex - px
    local dy = ey - py
    local dz = ez - pz
    if dx * dx + dy * dy + dz * dz <= radiusSqr then
        playersInRadius[count + 1] = p
        count = count + 1
    end
end
```

Reason: Direct player iteration with squared distance check avoids entity scanning and square root calculations.


```
for k=1, n do
    -- loop body
end
```

Reason: for loops in Lua are native and optimized, avoiding the condition check each iteration that while loops require.


```lua
-- Fast: Single hook call with all players
hook.Run("CustomNotification", player.GetAll())
```

Reason: Single hook call reduces overhead compared to per-player iteration


```lua
hook.Add("HUDPaint", "HealthDraw", function()
    local ply = LocalPlayer()
    local hp = ply:Health()
    surface.SetDrawColor(255, 0, 0, 200)
    surface.DrawRect(10, 10, hp/2, 25)
end)
```

Reason: Reducing redundant `LocalPlayer()` and `Health()` calls by caching the references.


```lua
local white = Color(255, 255, 255)
for _, ent in ipairs(entities) do
    ent:SetColor(white)
end
```

Reason: Move color creation outside the draw loop to avoid repeated allocations.


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

Reason: Local variable lookup is faster than global table lookup in Lua.


```lua
local function OptimizedFunction()
    local player = LocalPlayer() -- Cache the result

    -- Use the cached player reference multiple times
    player:Kill()
    player:SetName("Optimized")
    player:PrintMessage(HUD_PRINTTALK, "Done!")
end
```

Reason: Caching the LocalPlayer() result avoids global lookup on each call.


```lua
local function are_players_facing_each_other(player1, player2, threshold)
    local v1 = player1:GetAimVector()
    local v2 = player2:GetAimVector()

    local dot = v1:Dot(v2)
    return dot > threshold
end
```

Reason: Dot product of normalized vectors gives cos(theta) directly, avoiding expensive math.acos while providing fast angle comparison.


```lua
SomeHelper(ply)
```

Reason: Method calls require additional overhead for vtable lookup and self-dereferencing, while standalone functions with explicit parameters have lower execution cost.


```lua
MsgN("[DEBUG] something = " .. tostring(something))
```

Reason: `MsgN()` is faster than `print()` as it directly writes to the console without internal Lua printing overhead and without returning the value.


```lua
-- Benchmark of different table iteration methods for large numeric arrays
local size = 1000000
local arr = {}
for i = 1, size do arr[i] = i end

-- pairs - iterates over ALL table entries (including metatable)
local function testPairs()
    local sum = 0
    for k, v in pairs(arr) do
        sum = sum + v
    end
    return sum
end

-- ipairs - efficient for sequential numeric arrays
local function testIpairs()
    local sum = 0
    for k, v in ipairs(arr) do
        sum = sum + v
    end
    return sum
end

-- numeric for - fastest for sequential arrays
local function testNumericFor()
    local sum = 0
    for i = 1, size do
        sum = sum + arr[i]
    end
    return sum
end

-- Run and compare
local pairsResult = testPairs()
local ipairsResult = testIpairs()
local numericForResult = testNumericFor()

print("pairs:", pairsResult)
print("ipairs:", ipairsResult)
print("numeric for:", numericForResult)
```

Reason: numeric for is fastest, pairs has overhead from all key lookup, ipairs yields nil after array ends.


Answer must contain 0 through 2 candidate loops.

```lua
local function map(list, fn)
    local result = {}
    for i = 1, #list do
        local val = list[i]
        if val then
            result[#result + 1] = fn(val)
        end
    end
    return result
end

local function filter(list, predicate)
    local result = {}
    for i = 1, #list do
        local val = list[i]
        if val and predicate(val) then
            result[#result + 1] = val
        end
    end
    return result
end

local function pipeline(data, operations)
    local result = data
    for i = 1, #operations do
        local op = operations[i]
        local func = op.fn
        local args = op.args or {}

        if op.type == 'map' then
            result = map(result, func(unpack(args)))
        elseif op.type == 'filter' then
            result = filter(result, func(unpack(args)))
        end
    end
    return result
end
```

Reason: Uses direct table iteration and pre-allocated results for faster list transforms than fn combinators.


```lua
local player_cache = {}
local dirty = false

local function refresh_cache()
    player_cache = {}
    for i, ply in ipairs(player.GetAll()) do
        player_cache[i] = ply
    end
    dirty = false
end

hook.Add("PlayerInitialSpawn", "PlayerCache_Refresh", function()
    dirty = true
end)

hook.Add("PlayerDisconnected", "PlayerCache_Refresh", function()
    dirty = true
end)

hook.Add("Tick", "PlayerCache_Optimized", function()
    if dirty or #player_cache == 0 then
        refresh_cache()
    end

    for i, ply in ipairs(player_cache) do
        -- Process player
    end
end)

refresh_cache()
```

Reason: Cache players in a table and only refresh when changes occur, reducing player.GetAll() calls from every tick to only when players join/leave.


```lua
local PlayerData = {}
local playerIDToIndex = {}
local nextIndex = 1

function GetPlayerData(ply)
    local index = playerIDToIndex[ply:SteamID()]
    if not index then
        index = nextIndex
        nextIndex = nextIndex + 1
        playerIDToIndex[ply:SteamID()] = index
    end
    return PlayerData[index]
end

function AddPlayerData(ply)
    local data = {}
    local index = nextIndex
    nextIndex = nextIndex + 1
    PlayerData[index] = data
    playerIDToIndex[ply:SteamID()] = index
    return data
end

function RemovePlayerData(ply)
    local index = playerIDToIndex[ply:SteamID()]
    if index then
        PlayerData[index] = nil
        playerIDToIndex[ply:SteamID()] = nil
    end
end

-- Usage:
local function OnPlayerChat(ply, msg)
    local data = GetPlayerData(ply)
    data.lastChatTime = CurTime()
    data.chatCount = (data.chatCount or 0) + 1
end
```

Reason: Flat storage with integer indices avoids meta table lookups and property resolution overhead that Lua uses for per-player properties.


```lua
-- Performance comparison for table iteration in Garry's Mod Lua

local function test_string_map_iteration()
    local data = {}
    for i = 1, 100000 do
        data[tostring(i)] = i
    end

    local sum = 0
    local start = RealTime()
    for k, v in pairs(data) do
        sum = sum + v
    end
    return RealTime() - start
end

local function test_numeric_array_iteration()
    local data = {}
    for i = 1, 100000 do
        data[i] = i
    end

    local sum = 0
    local start = RealTime()
    for i = 1, #data do
        sum = sum + data[i]
    end
    return RealTime() - start
end

local string_map_time = test_string_map_iteration()
local numeric_array_time = test_numeric_array_iteration()

print("String map iteration time:", string_map_time)
print("Numeric array iteration time:", numeric_array_time)
print("Ratio (map/array):", string_map_time / numeric_array_time)
```

Reason: Numeric arrays are significantly faster for iteration in Garry's Mod Lua because direct numeric indexing avoids hash table lookups and the garbage collector handles them more efficiently.


`surface.SetDrawColor(255, 255, 255, 255)`

Reason: Passing separate r,g,b,a numbers directly to surface.SetDrawColor avoids the overhead of constructing a Color object, making it faster for hot draw paths where the function is called in tight loops.


```lua
local result = sql.Query("SELECT * FROM players WHERE steamid = @steamid", {steamid = playerStupidID})
```

Reason: SQLite has lower latency for single-game-server storage. It runs locally with no network overhead, memory-mapped file access, and less architecture complexity compared to remote MySQL which requires TCP/IP communication to a separate machine.


```lua
local STEAMID_CACHE = {}

function GetCachedSteamID(ply)
    if not STEAMID_CACHE[ply] then
        STEAMID_CACHE[ply] = ply:SteamID()
    end
    return STEAMID_CACHE[ply]
end

-- Usage instead of repeated ply:SteamID() calls:
-- local steamid = GetCachedSteamID(ply)
```

Reason: This caches SteamID results using player references as keys, eliminating redundant SteamID() lookups.


```lua
-- Inefficient: Repeated .. concatenation
local text = ""
for i = 1, 10000 do
    text = text .. "Piece " .. i .. "\n"
end
print(text)

-- Efficient: Using table + table.concat()
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "Piece " .. i .. "\n"
end
local text = table.concat(pieces)
print(text)
```

Reason: `..` concatenation creates intermediate strings each time, causing O(n²) memory allocation and copying, while `table.concat()` does a single allocation and copy.
```


```lua
local function fastRect(x, y, w, h)
    surface.SetDrawColor(color.r, color.g, color.b, color.a)
    surface.DrawRect(x, y, w, h)
end
```

Reason: draw.RoundedBox always computes corner radii even when they are all zero, creating unnecessary processing overhead. Direct surface calls like surface.DrawRect bypass this logic and are faster when rendering simple rectangles.


```lua
local font = surface.CreateFont("FastText", {
    font = "Tahoma",
    size = 16,
    weight = 400,
    antialias = true
})

local x, y = 100, 100
local text = "Performance Test"

draw.SimpleTextOutlined(
    text,
    font,
    x, y,
    color_white,
    1,
    color_black
)
```

Reason: draw.SimpleTextOutlined is fastest as it uses native draw calls without font creation overhead and renders text + outline in a single operation.


```lua
#myTable
```

Reason: The `#` operator is the idiomatic way to get the length of a sequential array-like table in Garry's Mod Lua.


```lua
-- t = {} creates a new empty table reference
local myTable = {}
for i = 1, 1000000 do
    myTable[i] = i
end

-- Faster: Just assign new empty table
local newTable = {}
for k, v in pairs(myTable) do
    -- Process or discard values
end
myTable = {}  -- Discards old table, gets new empty one

-- table.Empty(t) iterates through all elements to clear them
local anotherTable = {}
for i = 1, 1000000 do
    anotherTable[i] = i
end
table.Empty(anotherTable)  -- Slower: O(n) iteration
```

Reason: `t = {}` is generally faster as it's O(1) assignment vs `table.Empty(t)`'s O(n) iteration.


```lua
-- Create a set for O(1) lookup
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true,
}

-- Check membership (O(1) operation)
if mySet["value1"] then
    print("value1 exists in set")
end

-- Add new value
mySet["value4"] = true

-- Remove value
mySet["value2"] = nil
```

Reason: Using a table as a set with `key = true` enables O(1) dictionary lookup, while table.HasValue requires O(n) iteration through all list elements.


```lua
local myTable = {field1 = value1, field2 = value2}
```

Reason: Direct table construction avoids the intermediate empty table state, making it faster for small tables with known fields.


```lua
-- Get random element from sequential table (faster than table.Random)
local function getRandomElement(tbl)
    local randomIndex = math.random(#tbl)
    return tbl[randomIndex]
end
```

Reason: math.random provides O(1) access vs table.Random's O(n) Fisher-Yates shuffle for sequential tables.


```lua
x * x
```
Reason: Using direct multiplication (x * x) is faster than math.pow(x, 2) or x ^ 2 in Lua.


```lua
for k, v in pairs(player.GetAll()) do
    print("Player " .. k .. " is " .. v:Name())
end
```

Reason: This loop iterates over all connected players in Garry's Mod, accessing each player's entity ID (k) and the player object (v).