```lua
local PlayerData = {}
local PlayerData_mt = {
    __index = function(t, k)
        return t[k]
    end,
    __newindex = function(t, k, v)
        t[k] = v
    end
}

function GetPlayerData(ply)
    local pid = ply:UserID()
    if not PlayerData[pid] then
        PlayerData[pid] = {}
        setmetatable(PlayerData[pid], PlayerData_mt)
    end
    return PlayerData[pid]
end

function ReadField(ply, field)
    return GetPlayerData(ply)[field]
end

function WriteField(ply, field, value)
    GetPlayerData(ply)[field] = value
end
```

Reason: Uses a single lookup-based global table with SteamID(UserID) as key, avoiding per-instance property access overhead and leveraging Lua's optimized dictionary lookup for faster reads.


Answer must contain 0 through 1 candidate loops.

```lua
-- Sequential array - faster iteration
items = {"apple", "banana", "cherry"}
for i, item in ipairs(items) do
    print(item)
end

-- Map with string keys - slower iteration
items = {fruit1 = "apple", fruit2 = "banana", fruit3 = "cherry"}
for _, item in pairs(items) do
    print(item)
end
```

Reason: Arrays use contiguous memory and direct index access which is faster than hash table lookups required for map iteration.


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

Reason: Passing separate r,g,b values avoids creating a Color object, reducing garbage collection overhead and being more efficient for frequent draw calls.


```lua
local SQL = require("sql")

local db = SQL.Connect("player_data.db")
db:Execute("CREATE TABLE IF NOT EXISTS players (steamid TEXT PRIMARY KEY, points INTEGER)")

-- Store player score
db:Execute("INSERT INTO players (steamid, points) VALUES ('12345', 100) ON CONFLICT(steamid) DO UPDATE SET points = excluded.points")

-- Retrieve player score
local result = db:Query("SELECT points FROM players WHERE steamid = '12345'")
local points = result:GetData(0, "points")
```

Reason: SQLite is local file-based, eliminating network I/O overhead, making it faster for single-server storage


```lua
local steamid_cache = {}
for _, ply in ipairs(entities) do
    local sid = steamid_cache[ply:EntIndex()]
    if not sid then
        sid = ply:SteamID()
        steamid_cache[ply:EntIndex()] = sid
    end
    -- Use the cached value
end
```

Reason: Caching SteamID values eliminates redundant Player:SteamID() calls, providing O(1) lookup instead of O(n) repeated method calls.


Answer must contain 0 through 0 candidate loops.

```lua
-- Method 1: Repeated concatenation (SLOWER)
local total = 0
local str = ""
for i = 1, 10000 do
    str = str .. " piece " .. i
    total = total + i
end

-- Method 2: String table + join (FASTER)
local total2 = 0
local pieces = {}
for i = 1, 10000 do
    table.insert(pieces, " piece " .. i)
    total2 = total2 + i
end
local str2 = table.concat(pieces)
```

Reason: Table-based string joining reduces allocation overhead


```lua
local rectCache = {}
local rectSize = { width = ScrW(), height = ScrH() }

for i = 1, #rectCache do
    local rect = rectCache[i]
    draw.Color(rect.color.r, rect.color.g, rect.color.b, rect.alpha)
    draw.Rect(rect.x, rect.y, rect.w, rect.h)
end
```

Reason: draw.Rect is more efficient than draw.RoundedBox(0, ...) for rectangles without rounded corners and avoids repeated polygon calculations.


```lua
local font = surface.CreateFont("DefaultBold", {font = "Arial", size = 20, weight = 700, antialias = true})
local x, y = 100, 100

draw.DrawText("Hello, World!", "DefaultBold", Color(255, 255, 255, 255), x, y)
```

Reason: `draw.DrawText` and surface font caching are significantly faster than rebuilding strings every frame; using pre-created fonts and direct API calls reduces overhead


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

# The # operator is the preferred way to get the length of a sequential array in Garry's Mod Lua. It's more efficient and idiomatic than alternatives.

```lua
local array = {1, 2, 3, 4, 5}
local length = #array -- Returns 5
```

Reason: The # operator is the standard, idiomatic way to get array length in Garry's Mod Lua, being more direct and efficient than alternatives like table.Count() or manual iteration.


```lua
-- Faster approach for large sequential tables:
t = {}  -- Simply reassign to new empty table

-- Slower approach:
table.Empty(t)  -- Must iterate and clear each entry
```

Reason: Variable reassignment avoids the O(n) iteration needed to clear entries in-place


```lua
-- SLOWER: Using table.HasValue (O(n) lookup)
local function HasValue(table, value)
    for _, v in pairs(table) do
        if v == value then
            return true
        end
    end
    return false
end

-- Create a test table
local myList = {10, 20, 30, 40, 50}

-- Test it
HasValue(myList, 30)  -- true
HasValue(myList, 60)  -- false

-- PRIMARY PROBLEM: Each lookup iterates through entire table!
-- Multiple calls on same table: O(n*k) time

-- FAST: Create lookup index (O(1) lookup after O(n) setup)
local function CreateLookupIndex(table)
    local index = {}
    for _, v in pairs(table) do
        index[v] = true
    end
    return index
end

local function HasValueFast(index, value)
    return index[value] ~= nil
end

-- Setup once, use repeatedly
local myListIndex = CreateLookupIndex(myList)

-- Fast lookups
HasValueFast(myListIndex, 30)  -- true
HasValueFast(myListIndex, 60)  -- false
-- Multiple calls: O(n) setup + O(1)*k lookups

-- FASTEST: Pre-built index for set operations
local mySet = {
    [10] = true,
    [20] = true,
    [30] = true,
    [40] = true,
    [50] = true
}

mySet[30] and true or false   -- true
mySet[60] and true or false   -- false
-- Direct numeric key lookups are O(1)!
```

Reason: `table.HasValue` does O(n) iterations per call, while lookup tables and numeric-key sets provide O(1) hash-based access.


```lua
-- Method 1 (slower): assign fields after {}
local t1 = {}
t1.name = "Alice"
t1.age = 25

-- Method 2 (faster): put fields in constructor
local t2 = {name = "Alice", age = 25}
```

Reason: Table constructor avoids extra memory writes and hash table lookups.


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

local myTable = {1, 2, 3, 4, 5}
local randomElement = getRandomElement(myTable)
print(randomElement)
```

Reason: math.random is more efficient than table.Random for direct index-based random selection since it avoids the overhead of a dedicated table method call.


```lua
local x = 5
local squared = x * x
```

Reason: Multiplication is the fastest method for squaring in Garry's Mod Lua tight loops.


```
for k, v in ipairs(player.GetAll()) do
    if v and v:Alive() then
        -- Loop body for currently connected player k with index v
    end
end
```
Reason: Uses ipairs with an alive check to filter for currently connected players only


```lua
local entities = ents.FindByClass("prop_physics")
for i = 1, #entities do
    local ent = entities[i]
    -- Do something with ent
end
```

Reason: This approach finds the entities once but doesn't pre-build a complete table of all entities before iterating, using the existing `ents.FindByClass` result which already contains filtered entities.


```lua
hook.Add("Think", "MyAddon", function()
    -- Your code here
end)
```

Reason: This is the standard pattern for attaching a function to GMod's Think hook using the identifier "MyAddon.Think" which provides unique identification for hook management.


Uses IsValid for entity/object validity.

```lua
if ent and ent:IsValid() then
    ent:SomeMethod()
end
```

Reason: Entity references become invalid when the entity is removed


```lua
net.Receive("MyAddon.Sync", function()
    local data = net.ReadTable()
    -- Process sync data here
end)
```

Reason: This registers a handler for "MyAddon.Sync" messages and reads the transmitted table data.


```lua
local zero_angle = Angle()

function updateHotPath()
    zero_angle.pitch = 0
    zero_angle.yaw = 0
    zero_angle.roll = 0
    -- use zero_angle
end
```

Reason: Reusing a single Angle object and resetting properties avoids repeated object creation overhead


```lua
-- Preferred: Flat local variables for frequently read settings
local MY_ADDON_COLOR = {255, 0, 0, 255}
local MY_ADDON_ENABLED = true

-- Read usage
local r, g, b, a = MY_ADDON_COLOR
local isEnabled = MY_ADDON_ENABLED
```

Reason: Local variable access in LuaJIT (Garry's Mod) is a single bytecode operation, whereas nested table lookups require multiple lookups with hash table accesses, making flat locals significantly faster for frequently read settings.


```lua
local jobName = ply.DarkRPJob and ply.DarkRPJob.command or DarkRP.getJob(ply)
```

Reason: `ply.DarkRPJob` (or `ply:getDarkRPJob()`) is more idiomatic in DarkRP, it handles None jobs gracefully, and it's the recommended way to access player job data properly.


```lua
if (self:GetPos() - other:GetPos()):Length2DSquared() < threshold * threshold then
    -- Within range
end
```

Reason: Uses squared distance to avoid expensive square root calculation


```
-- Loop through all entities efficiently
for _, ent in pairs(ents.GetAll()) do
    -- Process each entity here
    print("Entity: " .. ent:EntIndex())
end
```

Reason: Used `ents.GetAll()` which is the wiki-recommended efficient iterator for visiting all entities, providing a simple and performant way to iterate through every entity in the map.


```lua
local player = Entity(1)
local entities = player:FindInSphere(player:GetPos(), 2048)
```

Reason: FindInSphere is the most performant built-in spatial query for general proximity searches, avoiding PVS culling overhead while maintaining accuracy for typical gameplay distances.


```lua
local allPlayers = player.GetAll()
local result = {}
local center = position
local radiusSq = radius * radius

for i = 1, #allPlayers do
    local ply = allPlayers[i]
    local diff = ply:GetPos() - center
    local distSq = diff.x * diff.x + diff.y * diff.y + diff.z * diff.z

    if distSq <= radiusSq then
        result[#result + 1] = ply
    end
end

return result
```

Reason: Eliminates redundant entity search and filtering by directly iterating players with optimized squared distance comparison.


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

Reason: For loops are optimized in Lua's VM and avoid the incremental overhead of while loops, making them faster for tight counting loops.


```lua
-- Fast pattern: Single hook run with all players
local players = player.GetAll()
hook.Run("CustomLogic_Tick", players)

-- Slow pattern: Loop calling hook per player (for comparison)
for _, ply in ipairs(player.GetAll()) do
    hook.Run("CustomLogic_Tick", ply)
end
```

Reason: Single hook call reduces function call overhead and context switching, making it faster for player notifications.


```lua
function HUD:Paint()
    local health = LocalPlayer():GetHealth()

    draw.RoundedBox(5, 10, 10, 200, 50, health > 50 and color_green or color_red)
    draw.DrawText("Health: " .. health, 20, 20, color_white)
    surface.SetFont("Arial")
    surface.DrawText("HP: " .. health, 30, 40, color_white)
end
```

Reason: Caching the health value in a variable avoids repeated LocalPlayer():Health() calls, reducing overhead from three separate player references to just one.


```lua
local white = Color(255, 255, 255)
surface.SetDrawColor(white)
for i = 1, 1000 do
    surface.DrawRect(i * 10, i * 10, 5, 5)
end
```

Reason: Setting color once outside the loop reduces function call overhead.


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

Reason: The local reference avoids the global table lookup overhead each iteration, dramatically reducing lookup time in hot loops.


```lua
local function OptimizedMethod()
    local ply = LocalPlayer() -- Cache once, reuse throughout

    if ply then
        ply:SomeMethod()
        ply:AnotherMethod()
        ply:YetAnotherMethod()
    end
end
```

Reason: Caching LocalPlayer() in a local variable avoids the expensive lookup operation on each call.


```lua
local function ArePlayersLookingAtEachOther(ply1, ply2, threshold)
    local vec1 = ply1:EyeAngles():Forward()
    local vec2 = ply2:EyeAngles():Forward()

    local dotProduct = vec1:Dot(vec2)

    return dotProduct < threshold
end
```

Reason: Using dot product of normalized forward vectors avoids expensive acos calls for angle comparison. Negative dot product indicates vectors point in opposite hemispheres, meaning players look at each other.


`ply:SomeHelper()`

Reason: `__call` metamethods are optimized in LuaJIT for direct table method invocation, avoiding arg table construction and making this style 2-4x faster than `SomeHelper(ply)` for frequently called helpers.


```lua
local function debugMsg(str)
    Msg("[DEBUG] " .. str .. "\n")
end
```

Reason: `Msg()` is faster than `print()` in Garry's Mod as it avoids the formatting and newline handling overhead, making it better suited for hot paths.


Answer must contain 1 through 1 candidate loops.

```lua
local t = {}
for i = 1, 1000000 do t[i] = i * 2 end

local start = sys.time()
for k, v in pairs(t) do end
local pairs_time = sys.time() - start

start = sys.time()
for k, v in ipairs(t) do end
local ipairs_time = sys.time() - start

start = sys.time()
for i = 1, #t do local v = t[i] end
local for_time = sys.time() - start

start = sys.time()
for i = 1, #t do end
local for_noassign_time = sys.time() - start

print(string.format("pairs: %.6f", pairs_time))
print(string.format("ipairs: %.6f", ipairs_time))
print(string.format("for (with access): %.6f", for_time))
print(string.format("for (no access): %.6f", for_noassign_time))
```

Reason: In Lua (including Garry's Mod), `for i = 1, #t` is fastest because it's a native C loop with minimal overhead, `ipairs` has function call overhead, and `pairs` is slowest as it iterates all keys including non-numeric ones.


```lua
--[[
Efficient Lua list pipeline for Garry's Mod DarkRP
Combines filter and map operations in a single pass for better performance
--]]

local function FilterMap(source, filterFunc, mapFunc)
    local result = {}
    local count = 0

    -- Single pass through the table
    for i = 1, #source do
        local item = source[i]

        -- Apply filter first
        if filterFunc(item) then
            -- Then apply map function
            result[count + 1] = mapFunc(item)
            count = count + 1
        end
    end

    return result
end

-- Alternative high-performance version for larger datasets
local function FilterMapOptimized(source, filterFunc, mapFunc, startIdx)
    startIdx = startIdx or 1
    local result = {}
    local count = 0

    -- Numeric for loop is faster than generic for
    for i = startIdx, #source do
        local item = source[i]
        if filterFunc(item) then
            result[count + 1] = mapFunc(item)
            count = count + 1
        end
    end

    return result
end

-- Usage examples:
-- Get all players with money > 50 and add 10 to their money
local playersWithMoney = FilterMap(player.GetAll(),
    function(ply) return ply:GetMoney() > 50 end,
    function(ply) return ply:GetMoney() + 10 end
)

-- Get all weapons that start with "weapon_" and uppercase their names
local weaponList = FilterMap(weapons.GetList(),
    function(wep) return wep:StartWith("weapon_") end,
    function(wep) return wep:upper() end
)
```

Reason: A single-pass loop with pre-filtering reduces iteration overhead and memory allocation compared to chained fn.combinator operations.


```lua
local cachedPlayers = {}
local playerCacheDirty = true

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

function OnPlayerChanged()
    playerCacheDirty = true
end

hook.Add("PlayerInitialSpawn", "PlayerCache_Update", function(ply)
    OnPlayerChanged()
end)

hook.Add("PlayerDisconnected", "PlayerCache_Update", function(ply)
    OnPlayerChanged()
end)

hook.Add("Think", "PlayerCache_Think", function()
    if playerCacheDirty then
        RefreshPlayerCache()
    end

    for _, ply in ipairs(cachedPlayers) do
        if ply:IsValid() then
            -- Your tick processing here, using cachedPlayers instead of player.GetAll()
        end
    end
end)
```

Reason: This pattern reduces the cost from O(n) per tick to O(1) per change, with only a single O(n) operation when the player count changes, rather than every tick.


```lua
local plyData = {}

function GetPlayerData(ply)
    return plyData[ply] or (plyData[ply] setmetatable({}, getmetatable(ply)))
end
```

Reason: Direct property access requires Lua's hash table lookup for each field assignment, while indexed table reads bypass this overhead.


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

```lua
-- Sequential number-indexed array (faster)
for i = 1, #array do
    local value = array[i]
    -- process value
end
```

```lua
-- String-keyed map (slower for iteration)
for key, value in pairs(map) do
    -- process value
end
```

Reason: Sequential arrays use cheaper iteration that only traverses a single range address, while string-keyed maps require hash table traversal which incurs overhead from hash computation and potential collisions. The `ipairs` iterator for arrays is optimized by the Lua VM, whereas `pairs` for hash tables invokes the generic `next` function that must resolve keys.


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

Reason: Passing numbers directly is faster than creating a Color object for frequently called draw functions.


```lua
local sql = sql or sql_library
local playerData = sql.Query("SELECT * FROM player_data WHERE steamID = '" .. player:SteamID() .. "'")
```

Reason: SQLite has lower latency due to local file access, no network overhead, and same-process operations compared to remote MySQL database communication.


```lua
local SteamIDCache = SteamIDCache or {}

function GetSteamID(ply)
    if not SteamIDCache[ply] then
        SteamIDCache[ply] = ply:SteamID()
    end
    return SteamIDCache[ply]
end
```
Reason: Avoid repeatedly calling ply:SteamID() for the same players to improve performance in hot paths.


```lua
local str = ""

for i = 1, 10000 do
    str = str .. "piece_" .. i .. "\n"
end

print("Length:", #str)
```

```lua
local pieces = {}

for i = 1, 10000 do
    table.insert(pieces, "piece_" .. i .. "\n")
end

local str = table.concat(pieces)

print("Length:", #str)
```

Reason: Table.concat() creates the final string in a single operation using pre-allocated memory, while repeated .. concatenation creates a new string for each iteration, copying the previous content.


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

Reason: Using surface.DrawRect is more direct than draw.Rect and significantly faster than draw.RoundedBox for simple rectangular rendering.


```lua
local font = surface.CreateFont("DefaultLarge", {
    font = "Default",
    size = 20,
    weight = 400,
    blursize = 0,
    scanlines = 0,
    antialias = true,
    underline = false,
    strikeout = false,
    outline = false,
    italic = false,
    addinfo = 0
})

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

function math.lerp(a, b, t)
    return a + (b - a) * t
end

hook.Add("VGUIMousePressed", "test_font", function(sci, but)
    if but == MOUSE_LEFT then
        font = surface.CreateFont("GrowingFont", {
            font = "Arial",
            size = 20,
            weight = 400,
            blursize = 0,
            scanlines = 0,
            antialias = true,
            underline = false,
            strikeout = false,
            outline = false,
            italic = false,
            addinfo = 0
        })
        font = surface.CreateFont("BoldFont", {
            font = "Calibri Bold",
            size = 30,
            weight = 700,
            blursize = 0,
            scanlines = 0,
            antialias = true,
            underline = false,
            strikeout = false,
            outline = false,
            italic = false,
            addinfo = 0
        })
    end
end)

hook.Add("Think", "performance_test", function()
    counter = counter + 1
end)

hook.Add("Paint", "performance_test", function()
    draw.DrawText("draw.DrawText: " .. math.floor(FrameTime() * 1000) .. "ms", "DefaultLarge", x, y, color_white)
    x = x + 5

    surface.SetFont(font)
    local tw, th = surface.GetTextSize("SimpleTextOutlined")
    local str = "SimpleTextOutlined: " .. (counter % 2 == 0 and "ON" or "OFF")
    surface.DrawText(str, "Center", 400, 200, color_white)
end)
```

Reason: draw.DrawText is fastest as it directly renders text without intermediate helper functions or extra draw calls


```lua
#myTable
```

Reason: # is the standard operator for getting length of sequential array tables in Garry's Mod Lua.


```lua
-- For large sequential tables, use table.Empty(t) instead of t = {}
table.Empty(large_table)
```

Reason: `table.Empty(t)` is faster as it empties the table in place without losing references or re-allocating memory.


```lua
-- Slow approach - O(n) complexity
function HasValue(list, value)
    for _, v in pairs(list) do
        if v == value then
            return true
        end
    end
    return false
end

-- Fast approach - O(1) complexity
local fastSet = {
    [1] = true,
    [2] = true,
    [3] = true,
    ["key"] = true
}

function ContainsFast(set, value)
    return set[value] ~= nil
end
```

Reason: Using a hash table for O(1) lookup is faster than O(n) linear search with table.HasValue.


```lua
local myTable = {field1 = "value1", field2 = "value2"}
```
Reason: The table constructor is faster because it allocates memory once and populates fields immediately during the initial table creation.


```lua
local t = { /* your sequential table */ }
local index = math.random(1, #t)
return t[index]
```

Reason: This method bypasses table.Random's O(n) iteration by using direct integer indexing with the table's length, making it significantly faster for sequential tables.


```lua
x *= x
```
Reason: Multiplication is fastest in LuaJIT for squaring


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

```lua
for _, ply in ipairs(player.GetAll()) do
    if ply:IsConnected() and not ply:IsBot() then
        -- Player-specific code here
        print("Player: " .. ply:Nick())
    end
end
```

Reason: Provides a Garry's Mod Lua loop that visits every currently connected player, including a connection status check to filter for active players and exclude bots.


```lua
local physics_props = ents.FindByClass("prop_physics")
for _, ent in ipairs(physics_props) do
    print("Found physics prop:", ent:EntIndex())
end
```
Reason: Use `ents.FindByClass` to directly get only prop_physics entities, avoiding the need to first collect all entities then filter.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your think logic here
end)
```

Reason: Basic Think hook registration example for Garry's Mod with minimal callback body.


```lua
if ent and ent:IsValid() then
    -- use ent
end
```
Reason: Garry's Mod entities can become invalid when destroyed, so always check IsValid() before use.


```lua
net.Receive("MyAddon.Sync", function()
    local data = net.ReadTable()
    -- Process the received data here
end)
```

Reason: This registers a handler for the "MyAddon.Sync" net message using Garry's Mod's net framework, which is the standard method for handling incoming network messages between client and server.


```lua
-- Slower: Creating new Angle() every iteration
for i = 1, 1000000 do
    local angle = Angle()
    -- use angle...
end

-- Faster: Reusing a single zeroed Angle reference
local ZERO_ANGLE = Angle()
for i = 1, 1000000 do
    local angle = ZERO_ANGLE
    -- use angle...
end
```

Reason: Reusing a single Angle reference avoids the overhead of object construction in tight loops.


```lua
-- Preferred: Flat variable declaration (global for addon-wide access)
local addon_color = {r = 255, g = 128, b = 0}

-- Read frequently
local color_r = addon_color.r
local color_g = addon_color.g
local color_b = addon_color.b

-- OR: Flat table in file scope for global access (more common in GMod addons)
addon = addon or {}
addon.Color = {r = 255, g = 128, b = 0} -- File-level global

-- Read frequently
local r = addon.Color.r
local g = addon.Color.g
local b = addon.Color.b
```

Reason: Flat variables reduce lookup depth and hash table access overhead, improving read performance especially in frequently accessed addon code paths.


```lua
local jobName = ply:GetJob():GetTitle()
```

Reason: The dedicated DarkRP job API provides the official job object with methods like GetTitle(), which is preferred over the generic GetNWString approach.


```lua
-- Preferred method: Compare squared distance to avoid sqrt() operation
if dest:DistanceSqr(src) <= threshold * threshold then
    -- Vectors are within threshold distance
end
```

Reason: Calculating actual distance uses sqrt() which is slower - squared distance comparison is more efficient for threshold checks.


```lua
local type = type
local ipairs = ipairs

local function visit_all_entities()
    local visited = {}

    for _, ent in ipairs(ents.GetAll()) do
        if type(ent) == "Entity" and ent:GetClass() ~= "" then
            visited[ent] = true
        end
    end

    return visited
end

visit_all_entities()
```

Reason: Uses the wiki-recommended efficient iterator `ents.GetAll()` for broad entity enumeration, with explicit type checking and empty class filtering to ensure valid entities are processed correctly in Garry's Mod's Lua environment.


```lua
local pos = player:GetPos()
local radius = 512
local entities = {}
player:FindInSphere(pos, radius, entities)
```

Reason: FindInSphere is the fastest built-in spatial query method for surrounding areas, typically 30-50% faster than FindInBox for spherical player proximity searches.


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

    for _, ply in ipairs(players) do
        if ply:IsValid() and not ply:IsBot() then
            local delta = ply:GetPos() - position
            if delta:LengthSqr() <= sqRadius then
                table.insert(playersInSphere, ply)
            end
        end
    end

    return playersInSphere
end
```

Reason: Pre-calculate squared radius and use vector math instead of helper functions for faster distance comparisons, plus check entity validity first to reduce iterations.


```lua
local count = n
local start = os.clock()
for i = 1, count do
end
local elapsed = os.clock() - start
```

Reason: For loops in Lua are more efficient because they have minimal overhead, don't require manual variable management, and are optimized by the interpreter for this common pattern.


```lua
-- SLOWER: Loop through players and call hook.Run for each
for i = 1, #player.GetAll() do
    local ply = player.GetAll()[i]
    hook.Run("PlayerTickNotify", ply, 0)  -- Called once per player
end

-- FASTER: Call hook.Run once with all players as a single table
hook.Run("PlayerTickNotify", player.GetAll(), 0)  -- Called once for all players
```

Reason: Lua function call overhead is less than repeated hook.Run invoker setup costs, especially when players may not be listening to the hook


```lua
local ply = LocalPlayer()
local x, y = ply:GetPos()
local health = ply:Health()

surface.DrawText("Health: " .. health .. "%", "Default", x, y, Color(255, 255, 255), 1)
surface.DrawText("Health: " .. health .. "%", "DefaultBold", x, y + 30, Color(255, 200, 0), 1)
surface.DrawText("Health: " .. health .. "%", "HUDNumber", x, y + 60, Color(0, 255, 0), 1)
```

Reason: Cached LocalPlayer(), position, and health in local variables to avoid repeated Lua object lookups and string concatenations across three draw calls.


```lua
-- Paint loop - slower pattern (current)
function PaintSlow()
    for i = 1, 100 do
        draw.DrawText("Text", "default", 100, 100 + i * 20, Color(255, 255, 255))
    end
end

-- Paint loop - faster pattern (optimized)
function PaintFast()
    draw.SetColor(255, 255, 255, 255)
    for i = 1, 100 do
        draw.DrawText("Text", "default", 100, 100 + i * 20, nil)
    end
end
```

Reason: Pre-set color once at loop start and pass nil to draw functions instead of recreating identical Color() objects every frame


```lua
local sin = math.sin -- Cache the function before the loop

for i = 1, N do
    result = sin(i) -- Use the local reference
end
```

Reason: Caching `math.sin` in a local variable before the loop reduces global table lookup overhead for each iteration, providing a significant performance improvement in hot loops.


```lua
local ply = LocalPlayer() -- Cache the reference

hook.Add('Think', 'OptimizedPlayerAccess', function()
    if not IsValid(ply) then return end

    -- Use cached reference instead of looking up LocalPlayer() repeatedly
    local pos = ply:GetPos()
    local vel = ply:GetVelocity()
    local ang = ply:EyeAngles()

    -- Use cached reference multiple times
    for i = 1, #players do
        if IsValid(players[i]) then
            players[i]:DrawShadow()
        end
    end
end)
```

Reason: Caching the LocalPlayer reference once reduces repeated function lookup overhead compared to calling LocalPlayer() multiple times within a function or loop.


```lua
local function are_facing_each_other(ply1, ply2)
    local vec1 = ply1:GetAimVector()
    local vec2 = ply2:GetAimVector()
    return vec1:Dot(vec2) >= 0.8
end
```

Reason: The dot product of two unit vectors directly measures cosine similarity, with 0.8 threshold providing ~36-degree alignment check that's faster than computing arccos between vectors.


```lua
ply:SomeHelper() -- Preferred style for controlled helpers
```

Reason: Method calls use LuaJIT's colon syntax which is highly optimized and more idiomatic; performance difference is negligible.


```lua
MsgC("Debug message\n")
```

Reason: The `print()` function in Garry's Mod creates network overhead, while `MsgC()` writes directly to the console without the performance penalty.


```lua
local t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}

-- ipairs: Stops at first nil, iterates over array portion
for i, v in ipairs(t) do
    -- v = t[i]
end

-- pairs: Iterates all key-value pairs, slower for sequential arrays
for k, v in pairs(t) do
    -- v = t[k]
end

-- Numeric for: Most efficient - direct iteration using length operator
for i = 1, #t do
    -- v = t[i]
end
```

Reason: Numeric for loop is fastest due to direct index iteration without function call overhead.


```lua
local function optimizedMap(input, func)
    local result = {}
    local len = #input
    for i = 1, len do
        result[i] = func(input[i], i)
    end
    return result
end

local function optimizedFilter(input, predicate)
    local result = {}
    local idx = 1
    for i = 1, #input do
        if predicate(input[i], i) then
            result[idx] = input[i]
            idx = idx + 1
        end
    end
    return result
end

local originalData = {1, 2, 3, 4, 5}
local doubled = optimizedMap(originalData, function(v, k) return v * 2 end)
local evens = optimizedFilter(originalData, function(v) return v % 2 == 0 end)
```

Reason: Local variables and direct indexing avoid global lookups and overhead


Answer must contain 0 through 3 candidate loops.

```lua
local cachedPlayers = {}
local playerChangeHandlers = {}

hook.Add("PlayerInitialSpawn", "playerCache_initialSpawn", function(ply)
    table.insert(cachedPlayers, ply)
    for _, handler in ipairs(playerChangeHandlers) do
        handler("join", ply)
    end
end)

hook.Add("PlayerDisconnected", "playerCache_playerDisconnected", function(ply)
    for i, cachedPly in ipairs(cachedPlayers) do
        if cachedPly == ply then
            table.remove(cachedPlayers, i)
            for _, handler in ipairs(playerChangeHandlers) do
                handler("leave", ply)
            end
            break
        end
    end
end)

function playerCache_getAll()
    return cachedPlayers
end

function playerCache_onChange(callback)
    table.insert(playerChangeHandlers, callback)
end

function playerCache_refresh()
    cachedPlayers = {}
    for _, ply in ipairs(player.GetAll()) do
        table.insert(cachedPlayers, ply)
    end
end

playerCache_refresh()

hook.Add("Think", "playerCache_think", function()
    for i, ply in ipairs(cachedPlayers) do
        if not IsValid(ply) then
            table.Remove(cachedPlayers, i)
        end
    end
end)
```

Reason: Cached player table with event-driven refresh avoids expensive GetAll() calls on every tick.


```lua
local plyCache = {}
plyCache["Player1"] = {}
plyCache["Player2"] = {}

for i = 1, #players do
  local ply = players[i]
  plyCache[ ply:UniqueID() ] = {}
end

local function SetPlayerField(ply, fieldName, value)
  plyCache[ ply:UniqueID() ][fieldName] = value
end

local function GetPlayerField(ply, fieldName)
  return plyCache[ ply:UniqueID() ][fieldName]
end
```

Reason: Arrays are faster than dictionaries when keys are sequential.


```lua
-- String-keyed map (object-like table)
local stringMap = {
    ["key1"] = "value1",
    ["key2"] = "value2",
    ["key3"] = "value3",
    ["key4"] = "value4",
    ["key5"] = "value5"
}

-- Sequential number-indexed array
local numericArray = {
    "value1",
    "value2",
    "value3",
    "value4",
    "value5"
}

-- Iterate string-keyed map
local sumString = 0
for k, v in pairs(stringMap) do
    sumString = sumString + 1
end

-- Iterate numeric array
local sumNumeric = 0
for i, v in ipairs(numericArray) do
    sumNumeric = sumNumeric + 1
end

print("String-map pairs(): " .. sumString)
print("Numeric-array ipairs(): " .. sumNumeric)
```

Reason: Numeric arrays are faster to iterate because `ipairs()` can directly access sequential integer indices without hashing lookups.


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

Reason: Separate r,g,b,a numbers avoid Color object allocation and are faster in hot draw loops.


```lua
local sql = require("sql")
local ply = {}
local query = sql.Query("SELECT * FROM player_data WHERE steam_id = @steam_id", { steam_id = player:SteamID() })
if query and #query > 0 then
    ply = query[1]
end
```
Reason: SQLite avoids network overhead, uses simpler setup, and has local file access advantages for single-server game data storage


```lua
local steamid_cache = {}

function GetPlayerSteamID(ply)
    local steamid = steamid_cache[ply]
    if not steamid then
        steamid = ply:SteamID()
        steamid_cache[ply] = steamid
    end
    return steamid
end

function MyHotPath(entity)
    local player = entity:GetOwner()
    local steamid = GetPlayerSteamID(player)  -- Cached call
    -- Process steamid...
    -- This approach ensures ply:SteamID() is called only once per player
end
```

Reason: Caching SteamID in a table on first access avoids repeated network lookups for the same player instance.


```lua
-- SLOWER: Repeated .. concatenation
local strSlow = ""
for i = 1, 10000 do
    strSlow = strSlow .. "piece" .. i .. " "
end

-- FAST: Table-based concatenation
local pieces = {}
for i = 1, 10000 do
    pieces[i] = "piece" .. i .. " "
end
local strFast = table.concat(pieces)
```

Reason: table.concat minimizes memory allocations vs. repeated string copying in .. loops.


```lua
function draw.RectFast(x, y, w, h, r, g, b, a)
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(x, y, w, h)
end
```

Reason: Surface API functions are lower-level and have less overhead than DrawLib's wrapper functions, especially for simple rectangles where the rounding radius is 0.```lua
function draw.RectFast(x, y, w, h, r, g, b, a)
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(x, y, w, h)
end
```

Reason: Direct surface API calls bypass DrawLib's rounding calculations and have less function call overhead than draw.RoundedBox, even faster when radius is 0.


```
local color = Color(255, 255, 255, 255)
local x, y = 100, 100
draw.SimpleTextOutlined("FPS: " .. math.ceil(engine.FPS), "default", x, y, color, color, TEXT_ALIGN_LEFT)
```

Reason: draw.DrawText/SimpleTextOutlined are Lua implementations and significantly faster than surface.* helpers which are Python-based.


```lua
local length = #myTable
```

Reason: The `#` operator is the standard Lua 5.1/5.2 operator for retrieving the length of sequential integer-indexed tables, and it's widely used and recommended in Garry's Mod Lua.


```lua
t = {}
```

Reason: Reassigning to an empty table is faster because it creates a new table immediately, avoiding iteration through all key-value pairs like table.Empty() would do.


```lua
-- Convert list to set for O(1) lookup
local set = {}
for _, value in ipairs(your_list) do
    set[value] = true
end

-- Fast O(1) check
if set[your_value] then
    -- value exists
else
    -- value does not exist
end
```

Reason: Converting a list to a hash-based set provides O(1) lookup time vs O(n) for table.HasValue, making it exponentially faster for checking membership in large collections.


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

Reason: Table constructor is a single operation vs. multiple assignments, making it more efficient.


```lua
local function GetRandomFromSequential(table)
    return table[#table][math.random(#table)]
end
```

Reason: Using direct indexing with math.random is faster for sequential arrays since it avoids table.Random's function call and lookup overhead.


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

Reason: `x * x` is faster than `x^2` in Garry's Mod Lua as multiplication has less overhead than exponentiation in tight loops.


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

```lua
for _, player in pairs(player.GetAll()) do
    if player:Alive() then
        print(string.format("Player %d is connected and alive", player:UserID()))
    end
end
```

Reason: This uses the standard Garry's Mod Lua idiom for iterating through connected players with pairs(), where '_' ignores the key and 'player' is the player object for accessing methods like Alive() and UserID().