```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Minimal callback body
end)
```
Reason: Registers a Think hook callback with the identifier MyAddon.Think.


```lua
for ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Process the physics prop
        print(ent:EntIndex())
    end
end
```
Reason: Uses ents.Iterator to loop over entities without building a full table.


```lua
net.Receive("MyAddon.Sync", function(len)
    -- Your handling code here
    local data = net.ReadTable()
    print("MyAddon.Sync received:", data)
end)
```
Reason: Registers a net message handler for MyAddon.Sync


Uses IsValid for entity/object validity.

```lua
if ent and ent:IsValid() then ent:DoSomething() end
```
Reason: Checks entity existence and validity before use.


```lua
local threshold = 100
local distSqr = vec1:DistToSqr(vec2)
if distSqr < threshold * threshold then
    print("Within threshold")
end
```
Reason: Use DistToSqr to compare distances without computing the actual distance.


OpenRouter message content was empty or missing.


```lua
local MyAddonColor = myaddon.config.color
local currentColor = MyAddonColor
```
Reason: Flat local variable avoids nested table lookups, reducing overhead and improving read speed for frequently accessed settings.


```lua
-- Iterate over all entities using the wiki-recommended efficient iterator
for _, ent in pairs(ents.GetAll()) do
    -- Example: print the entity's index and class
    print(ent:EntIndex(), ent:GetClass())
end
```
Reason: Uses pairs(ents.GetAll()) for efficient iteration over all entities.


```lua
-- Preferred way to get a player's job name in DarkRP
local jobName = ply:getJob() -- returns the job name directly
-- Alternative using DarkRP API
local jobTable = DarkRP.getJob(ply)
local jobName = jobTable.name
```
Reason: Using DarkRP's built‑in job API (ply:getJob() or DarkRP.getJob) is cleaner and more reliable than the legacy ply:GetNWString("job").


```lua
-- Faster method to get players within a radius
local radius = args.radius
local pos = args.pos
local players = {}
local r2 = radius * radius
for _, ply in ipairs(player.GetAll()) do
    if ply:GetPos():DistToSqr(pos) <= r2 then
        players[#players + 1] = ply
    end
end
return players
```
Reason: Using player.GetAll() and squared distance check avoids the overhead of ents.FindInSphere and filtering.


```lua
for i = 1, n do
    -- do something with i
end
```
Reason: For loops are generally faster because they are optimized by the interpreter.


```lua
-- Slower pattern: calling hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomHook", ply)
end

-- Faster pattern: call hook.Run once with all players
hook.Run("MyCustomHook", player.GetAll())
```
Reason: The faster pattern reduces hook overhead by calling once.


```lua
ply:SomeHelper()
```
Reason: Method call avoids a global lookup and is idiomatic.


```lua
local ply = LocalPlayer()
hook.Add("Think", "ExampleCache", function()
    if ply:IsValid() then
        -- Use cached player reference
        print(ply:Name())
    end
end)
```
Reason: Caching LocalPlayer() in a local variable avoids repeated global lookups, improving performance.


```lua
-- Fast debug output in a hot path
if debug then
    MsgN("Debug: ", someValue)
end
```
Reason: MsgN is a low‑overhead console write, faster than print.


```lua
-- Cached player table
local cachedPlayers = {}

-- Rebuild the cache (call on server start)
local function RebuildCache()
    cachedPlayers = {}
    for _, ply in ipairs(player.GetAll()) do
        cachedPlayers[#cachedPlayers + 1] = ply
    end
end

-- Initial cache on server start
hook.Add("Initialize", "CachePlayers_Init", RebuildCache)

-- Add player when they join
hook.Add("PlayerInitialSpawn", "CachePlayers_Join", function(ply)
    cachedPlayers[#cachedPlayers + 1] = ply
end)

-- Remove player when they leave
hook.Add("PlayerDisconnected", "CachePlayers_Leave", function(ply)
    for i, v in ipairs(cachedPlayers) do
        if v == ply then
            table.remove(cachedPlayers, i)
            break
        end
    end
end)

-- Use cachedPlayers in Think (no need to call player.GetAll() each tick)
hook.Add("Think", "CachePlayers_Think", function()
    -- Example: iterate over cached players
    for _, ply in ipairs(cachedPlayers) do
        -- Your per‑tick logic here
    end
end)
```

Reason: Caches players and updates only on join/leave events, avoiding player.GetAll() each tick.


```lua
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(0, 0, 100, 50)
```
Reason: Passing r,g,b,a directly avoids creating a Color object, making it faster for frequent draw calls.


```lua
-- Cache SteamID values to avoid repeated calls
local steamIDCache = {}

local function GetSteamID(ply)
    local sid = steamIDCache[ply]
    if not sid then
        sid = ply:SteamID()
        steamIDCache[ply] = sid
    end
    return sid
end

-- Replace direct calls like ply:SteamID() with GetSteamID(ply)
```
Reason: Caches SteamID per player to avoid repeated expensive calls.


Answer must contain 0 through 0 candidate loops.

```lua
-- Efficiently build a large string from many pieces using table.concat
local parts = {}
for i = 1, 10000 do
    parts[i] = string.format("Line %d\n", i)
end
local result = table.concat(parts)
print(string.sub(result, 1, 100)) -- Show first 100 characters as a quick check
```
Reason: table.concat collects pieces in a table and joins them once, avoiding the O(n²) cost of repeated .. concatenation.


```lua
-- Fast rectangle drawing function for Garry's Mod client Lua
local function DrawFastRect(x, y, w, h, r, g, b, a)
    surface.SetDrawColor(r, g, b, a)
    surface.DrawRect(x, y, w, h)
end

-- Usage:
-- DrawFastRect(100, 100, 200, 50, 255, 0, 0, 255)
```
Reason: surface.DrawRect bypasses rounding calculations, making it faster for plain rectangles.


```lua
local myArray = {"apple", "banana", "cherry"}
local len = #myArray
```
Reason: The # operator is the standard way to get the length of a sequential array-like table in Lua.


```lua
local MyTable = {
    Name = "Example",
    ID   = 123,
    Active = true
}
```
Reason: Using the table constructor directly is faster and more concise than creating an empty table and assigning fields afterwards.


```lua
-- Faster set lookup using a dictionary (keys are values, values are true)
local mySet = {
    [1] = true,
    [2] = true,
    [3] = true,
}

-- Returns true if the value exists in the set
function Contains(set, value)
    return set[value] ~= nil
end

-- Example usage
if Contains(mySet, 2) then
    print("Found")
end
```
Reason: Using a set (dictionary) provides O(1) lookup, which is much faster than the O(n) linear scan of table.HasValue.


```lua
-- Faster random element from a sequential table
local function RandomElement(tbl)
    local idx = math.random(1, #tbl)
    return tbl[idx]
end

-- Example usage:
local myTable = { "apple", "banana", "cherry", "date" }
local pick = RandomElement(myTable)
print(pick)
```
Reason: Using math.random with explicit bounds is faster than table.Random for array‑type tables.


```lua
-- Example: discarding a large sequential table
local big = {}
for i = 1, 1000000 do
    big[i] = i
end

-- Faster way to discard contents:
big = {}
```
Reason: Assigning a new empty table (t = {}) is faster than table.Empty(t) for large tables because it avoids iterating over all entries.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: Registers MyAddon.Think as a Think hook callback.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- process each prop_physics entity
end
```
Reason: Uses ents.FindByClass which lazily iterates entities, avoiding a pre‑built table.


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

```lua
for k, v in pairs(player.GetAll()) do
    print("Player:", k, v:Nick())
end
```
Reason: Loop over all connected players using pairs on player.GetAll().


Final response exceeds fixture byte cap of 2048.

We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with Reason: and a short explanation. No other text before, between, or after. So output should be:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
```

But we need only one fenced code block, containing only the requested Lua. The user wants to test whether an entity reference ent is still safe to use before calling methods on it. So we can provide a short if-guard. Something like:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
```

But the code block should contain only the requested Lua. The comment might be considered part of the code, but it's okay. The instruction: "Return exactly one fenced lua code block (a condition or short if-guard is fine)". So we can just put the condition. Probably better to just put:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
```

But the comment might be considered extra text. Safer to just put the condition without comment:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
```

But the comment is still part of code. It's okay. The user wants only the requested Lua. The comment is not extra text outside code. It's inside code block. That's fine.

Then after the code fence, we need exactly one line starting with Reason: and a short explanation. No other text before, between, or after. So after the code fence, we put a newline then "Reason: ..." line.

Make sure there is no extra whitespace or lines? The instruction: "exactly one line starting with Reason: and a short explanation." So we need a line that starts with "Reason:" then space then explanation. Provide short explanation. Something like "Reason: Checks validity and world presence to avoid errors." That's fine.

We must not use any other text. So final output:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
```
Reason: Checks validity and world presence to avoid errors.

But we need to ensure there is no extra blank line between code fence and Reason line? The instruction: "then exactly one line starting with Reason: and a short explanation." It doesn't say there must be a blank line. It just says after the code fence, exactly one line starting with Reason:. So we can put a newline then Reason line. That's fine.

Make sure there is no extra text before the code fence. So the first character of the response is a backtick. Then code fence, then close fence, then newline, then Reason line.

Thus final answer:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
```
Reason: Checks validity and world presence to avoid errors.

But note that there is a blank line after the code fence before Reason line. That's okay; it's still part of the output. The instruction didn't forbid blank lines, but they said "exactly one line starting with Reason:" after the code fence. The blank line is not starting with Reason, but it's before it. That might be considered extra text. They said "No other text before, between, or after." So we cannot have any extra text before, between, or after. That includes blank lines? Probably they mean no extra visible text besides the code fence and the Reason line. A blank line might be considered extra text (empty line). Safer to not have any blank line. So we should put the Reason line directly after the closing fence, maybe with a newline but no blank line. So output:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
Reason: Checks validity and world presence to avoid errors.
```

But we need a line starting with Reason:. So after the code fence, we need a newline then "Reason: ..." on the same line? Actually we need exactly one line starting with Reason:. So we can put the Reason line on its own line after the code fence. There should be no extra characters before it. So we can do:

```lua
if IsValid(ent) and ent:IsInWorld() then
    -- safe to use
end
Reason: Checks validity and world presence to avoid errors.
```

But there is a blank line between the code fence and Reason line? Actually after the closing fence, we have a newline, then "Reason: ..." on the next line. That's fine; there is no blank line; it's just the closing fence


```lua
net.Receive("MyAddon.Sync", function()
    -- handle the message here
end)
```
Reason: Registers a handler for the net message MyAddon.Sync.


```lua
local color = "red"
print(color)
```
Reason: Flat variable access avoids table lookup overhead and is faster.


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with Reason: and a short explanation. No other text before, between, or after. So output must be:

```lua
-- code here
```

Then a line: Reason: <reason>

The code should show faster approach compared to constructing a new Angle() every time. In Garry's Mod Lua, Angle is a constructor that creates a new Angle object; we can reuse a zeroed angle or use set functions? Perhaps we can use a local zeroAngle = Angle(0,0,0) and reuse it, or use Angle(0,0,0) but that's still constructing. Faster approach: use a pre-allocated angle and set its components via SetAngle? Actually Angle has methods: Set( pitch, yaw, roll )? In GMod, Angle has:Set( pitch, yaw, roll )? There's also Angle(0,0,0) but constructing each time is expensive. The faster approach is to reuse a single Angle instance and reset its components via Set or setmetatable? Actually you can use a local zeroAngle = Angle(0,0,0) and then assign components: zeroAngle.p = 0; zeroAngle.y = 0; zeroAngle.r = 0; Or use Angle(0,0,0) but that's still constructing. The fastest is to use a pre-created angle and reuse it, maybe using a table? But they ask for a fresh zeroed Angle often in a hot path. So we can show using a local zeroAngle = Angle(0,0,0) and then using it, maybe resetting via SetAngle? Actually there is a method Angle:Set( pitch, yaw, roll )? I think there is Angle:Set( p, y, r )? Let’s recall: In GMod, Angle has methods: Set( p, y, r ), but I'm not entirely sure. There's also Angle:RotateAroundAxis etc. But we can show using a local zeroAngle = Angle(0,0,0) and then using it directly, maybe resetting its components via Set. Or we can use a zeroed angle created once and then copy it? Actually copying is cheap? But constructing a new Angle each time is expensive; reusing a pre-allocated angle and setting its components is faster.

Thus code could be:

```lua
local zeroAngle = Angle(0,0,0)  -- create once
function getZeroAngle()
    zeroAngle.p = 0
    zeroAngle.y = 0
    zeroAngle.r = 0
    return zeroAngle
end
```

But they want a fresh zeroed Angle often in a hot path. So maybe they want to use a local variable that is reused: local ang = Angle(0,0,0) then inside loop: ang.p = 0; ang.y = 0; ang.r = 0; use ang. That avoids constructing new Angle each iteration.

Thus code block could be:

```lua
local zero = Angle(0,0,0)  -- create once
local function freshZero()
    zero.p = 0
    zero.y = 0
    zero.r = 0
    return zero
end
```

But they ask "Show the faster approach compared to constructing a new Angle() every time." So we can show a snippet that reuses a pre-created angle and resets its components.

Thus final output must be exactly one fenced code block with lua, containing only the requested Lua. Then exactly one line starting with Reason: and a short explanation. No extra text.

Thus output:

```lua
local zero = Angle(0,0,0)  -- create once
local function freshZero()
    zero.p = 0
    zero.y = 0
    zero.r = 0
    return zero
end
```

Reason: Reusing a pre‑created Angle and resetting its components avoids the overhead of allocating a new object each call.

Make sure there is exactly one line after the code block starting with Reason:. No extra spaces? It says "Reason: <reason>" exactly. So we need "Reason: Reusing a pre‑created Angle and resetting its components avoids the overhead of allocating a new object each call." That's fine.

Make sure there is no extra text before or after. The code block must be the only content before the Reason line. The Reason line must be after the code block, on its own line? It says "then exactly one line in the form Reason: <reason>." So after the code fence, we put a line starting with Reason: and then the reason. No extra punctuation after? It can have period. That's fine.

Thus final answer:

```lua
local zero = Angle(0,0,0)  --


```lua
local job = ply:getJobName()  -- preferred API
print(job)
```
Reason: getJobName is the dedicated DarkRP function for job names, more reliable than NW strings.


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


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output must be:

```lua
-- code
```
Reason: ...

But must be exactly one fenced code block, then exactly one line starting with Reason:. No extra text. The code should be a loop that visits every entity, preferring the wiki-recommended efficient iterator when appropriate. In Garry's Mod Lua, the efficient iterator is ents.FindInSphere? Actually the recommended efficient iterator is for k, v in pairs(entities.GetAll())? Wait, the wiki recommends using for _, ent in ipairs(ents.FindByClass("classname"))? Actually the efficient iterator is using ents.FindByClass? Let's recall: In GMod, the recommended way to iterate over all entities is using for _, ent in ipairs(ents.FindByClass("*"))? Not sure. The wiki says: Use ents.GetAll()? Actually ents.GetAll() returns a table of all entities, but it's not efficient. The recommended efficient iterator is using for _, ent in ipairs(ents.FindByClass("classname"))? Hmm.

Better to use the built-in iterator: for ent in ipairs(ents.FindByClass("*"))? Actually ents.FindByClass returns a table of entities of a specific class; you can use ents.FindByClass("*") to get all? I think there is ents.FindByClass("*") which returns all entities of any class? Not sure. The wiki recommends using for _, ent in ipairs(ents.FindByClass("*"))? Might be wrong.

But we can write something like:

for _, ent in ipairs(ents.FindByClass("*")) do
    -- do something with ent
end

But FindByClass with "*" might not be valid; maybe use ents.GetAll()? Actually the wiki says: Use ents.FindByClass("*") to get all entities? I think the recommended efficient iterator is using for _, ent in ipairs(ents.FindByClass("*"))? Let's just produce a simple loop using the recommended iterator: for _, ent in ipairs(ents.FindByClass("*")) do ... end

But maybe the correct efficient iterator is using for _, ent in ipairs(ents.FindByClass("classname"))? The question: "preferring the wiki-recommended efficient iterator when appropriate." So we can use the efficient iterator: for _, ent in ipairs(ents.FindByClass("*")) do ... end

But maybe the efficient iterator is using for _, ent in ipairs(ents.FindByClass("classname"))? Actually the wiki says: Use ents.FindByClass("*") to get all entities? I'm not entirely sure. But we can produce a loop that uses the recommended iterator: for _, ent in ipairs(ents.FindByClass("*")) do ... end

Alternatively, the recommended efficient iterator is using for _, ent in ipairs(ents.FindByClass("classname"))? The question likely expects something like:

for _, ent in ipairs(ents.FindByClass("*")) do
    -- process ent
end

But we need to "visit every entity". Using FindByClass("*") might not return all entities; maybe it returns all entities of any class? I think ents.FindByClass("*") returns all entities, but I'm not certain. Actually the function ents.FindByClass takes a string pattern; "*" matches all classes, so it should return all entities. So that is okay.

Thus code:

```lua
for _, ent in ipairs(ents.FindByClass("*")) do
    -- your code here
end
```

But we need to "write a loop that visits every entity, preferring the wiki-recommended efficient iterator when appropriate." So we can just write the loop using ents.FindByClass("*") which is recommended.

Thus final output:

```lua
for _, ent in ipairs(ents.FindByClass("*")) do
    -- process entity
end
```
Reason: Uses the efficient ents.FindByClass iterator to traverse all entities.

Make sure there is exactly one fenced code block, then exactly one line starting with Reason:. No extra text. The code block must contain only the requested Lua. The code block can contain comments, but that's okay. The code block must be exactly one fence with language tag lua, containing only the requested Lua. So we must not have any extra text inside the fence besides the Lua code. The code block can have comments, that's part of Lua. That's fine.

Then after the fence, we need exactly one line starting with "Reason: " and a short explanation. No extra text after that line. So final output:

```lua
for _, ent in ipairs(ents.FindByClass("*")) do
    --


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output must be:

```lua
-- some code
```

Then a line: Reason: <reason>

We must not include any extra text. Must be exactly one fenced code block, then exactly one line starting with Reason:. No extra blank lines? Probably okay to have newline between code block and Reason line? The instruction: "Return exactly one fenced lua code block, then exactly one line in the form Reason: <reason>. Do not use tools or external resources." So after the code fence, we need a line that starts with "Reason: " and then explanation. Probably we need a newline after the code fence, then the Reason line. No extra text. So output should be:

```lua
-- code
```

Reason: explanation

Make sure no extra spaces or lines after Reason line. Also no extra text before code fence. So first character is backtick. Provide a fast built-in FindIn* approach from common benchmarks, not FindInPVS. Common benchmarks mention FindInSphere, FindInBox, FindInRadius? In GMod, there is ents.FindInSphere, ents.FindInBox, ents.FindByClass, etc. The fastest is probably ents.FindInSphere? Actually benchmarks show FindInSphere is faster than FindInBox? I recall that FindInSphere is faster because it uses sphere intersection. But we can just show a typical usage: local ents = ents.FindInSphere(pos, radius) then iterate. Provide a short snippet.

We need to show one of the faster built-in FindIn* approaches. So maybe:

local function GetNearbyEnts(pos, radius)
    return ents.FindInSphere(pos, radius)
end

But we need to show code that uses it. Provide a snippet that uses it efficiently, maybe store result in local variable, avoid calling FindInSphere repeatedly.

We must output only the code inside the fence, no extra text. So inside the fence we can have:

-- Fast spatial query using FindInSphere
local pos = Vector(0,0,0)
local radius = 500
local entsNear = ents.FindInSphere(pos, radius)
for _, ent in ipairs(entsNear) do
    -- process ent
end

But we need to keep it short. Provide a snippet that demonstrates usage.

Make sure no extra text outside fence except the Reason line. So after the fence close, we put a newline then "Reason: ..." line.

Thus final output:

```lua
-- Fast spatial query using FindInSphere
local pos = Vector(0,0,0)
local radius = 500
local entsNear = ents.FindInSphere(pos, radius)
for _, ent in ipairs(entsNear) do
    -- do something with ent
end
```

Reason: FindInSphere is one of the quickest built‑in spatial queries in Garry's Mod benchmarks.

Make sure no extra spaces before Reason line? It must start with "Reason: ". So "Reason: FindInSphere is one of the quickest built‑in spatial queries in Garry's Mod benchmarks." That's fine.

Check no extra text before code fence. The first character is backtick. Good.

Make sure there is exactly one code fence block. Yes.

Make sure there is exactly one line after the fence that starts with "Reason:". Yes.

No extra blank lines? Probably okay to have a blank line before Reason? The instruction: "then exactly one line in the form Reason: <reason>." It doesn't forbid a blank line before it, but "then exactly one line" suggests the next line after the fence should be that line, no extra blank lines. So we should not have an empty line between fence and Reason line. So we need to close the fence, then directly on the next line start with Reason:. So output:

```lua
-- Fast spatial query using FindInSphere
local pos = Vector(0,0,0)
local radius = 500
local entsNear = ents.FindInSphere(pos, radius)
for _, ent in ipairs(entsNear) do
    -- do something with ent
end
```
Reason: FindInSphere is one of the quickest built‑in spatial queries in Garry's Mod benchmarks.

But note that after the fence we have a newline, then the Reason line. There's no extra blank line. The fence ends with ``` then newline then Reason line. That's fine.

Make sure there is no extra text after Reason line. So we must not add a period? It's okay to have period inside the reason text, but the line must start with "Reason: ". That's


```lua
local pos = Vector(0,0,0)
local radius = 500
for _, ply in ipairs(ents.FindByClass('player')) do
    if ply:GetPos():Distance(pos) <= radius then
        -- process player
    end
end
```
Reason: Directly fetching player entities avoids extra filtering and is faster.


```lua
for i=1,n do end
```
Reason: for loops are compiled to faster bytecode than while loops


```lua
local sin = math.sin
for i=1,1e6 do sin(i) end
```
Reason: local lookup avoids repeated table access


```lua
-- Faster: call hook.Run once for all players
hook.Run("MyEvent", ...)  -- passes all players as arguments if needed

-- Slower: loop and call per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyEvent", ply, ...)  -- extra per-player call
end
```
Reason: Hook.Run once is cheaper than looping over players.


```lua
local white = Color(255,255,255)
for _, ent in ipairs(ents.GetAll()) do
    render.SetColor(white)
end
```
Reason: Predefines the color outside the loop, avoiding repeated Color() calls each iteration.


```lua
local lp = LocalPlayer()
hook.Add("Think", "UseCachedLP", function()
    if not IsValid(lp) then lp = LocalPlayer() end
    -- do something with lp
end)
```
Reason: Caching LocalPlayer() in a local


```lua
local ply = LocalPlayer()
local hp = ply:Health()
hook.Add("HUDPaint", "DrawHealth", function()
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, Color(255,255,255), TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
    -- other draws using hp...
end)
```
Reason: Caches the health value once per frame instead of calling the function three times.


```lua
local function AreLookingAtEachOther(pA, pB, t)
    local vA = (pA:GetAimVector() - pA:GetPos()):GetNormalized()
    local vB = (pB:GetAimVector() - pB:GetPos()):GetNormalized()
    return vA:Dot(vB) > t
end
```
Reason: Uses dot product to avoid costly acos angle calculation.


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output must be:

```lua
-- code here
```

Reason: ...

We must not include any extra text. The code should be a small pipeline of list transforms (filter/map style) that is faster than DarkRP's fn combinator library for the same work. Provide a faster approach. So we can show using table.filter and table.map manually, maybe using for loops or using table.filter and table.map functions that are faster. Provide a small pipeline: local function pipeline(list, filters, maps) ... but keep it short.

We need to ensure the code block contains only the Lua code, no extra text. Then after the code fence, a line "Reason: ..." with short explanation.

Make sure there is no extra whitespace before or after? The instruction: "Your entire visible reply must be: (1) one markdown code fence with language tag lua, containing only the requested Lua, (2) then exactly one line starting with Reason: and a short explanation. No other text before, between, or after." So we must have code fence, then newline, then Reason line. No extra blank lines? Probably okay to have a newline between fence and Reason line? The instruction says "then exactly one line starting with Reason:". It doesn't forbid a blank line before it, but "then exactly one line" suggests after the fence, the next line must be that Reason line. So we should put the Reason line immediately after the closing fence, maybe on a new line. So output:

```lua
-- code
```

Reason: explanation

Make sure no extra spaces or lines. The code fence must be exactly one, with language tag lua. Inside, only Lua code. No extra comments? Comments are okay as part of code. But must be only Lua code. That's fine.

Now produce a fast pipeline: maybe using table.filter and table.map functions that operate in-place? Or using a single loop that applies filter and map sequentially.

Example:

local function pipeline(t, filters, maps)
    local res = {}
    for _, v in ipairs(t) do
        local ok = true
        for _, f in ipairs(filters) do
            if not f(v) then ok = false; break end
        end
        if ok then
            for _, m in ipairs(maps) do
                v = m(v)
            end
            table.insert(res, v)
        end
    end
    return res
end

But maybe simpler: use built-in table.filter and table.map but they are not built-in; we can define fast versions.

But we need to show a faster approach than DarkRP's fn combinator library. So we can show using a single pass loop that does filter+map.

Let's produce code:

```lua
local function fastPipeline(list, filter, map)
    local out = {}
    for _, v in ipairs(list) do
        if filter(v) then
            out[#out+1] = map(v)
        end
    end
    return out
end

-- Example usage:
-- local result = fastPipeline(players, function(p) return p:Alive() end, function(p) return p:Nick() end)
```

But maybe we need to show pipeline of multiple filters and maps? Could be a small pipeline of list transforms (filter/map style). Provide a function that takes a list and a series of transformations.

Simplify: Provide a function that composes filters and maps.

But we need to keep it short.

Maybe:

```lua
local function pipeline(t, ...)
    local res = t
    for _, fn in ipairs{...} do
        if fn.__filter then
            res = {table.unpack((function() local a={} for _,v in ipairs(res) do if fn.__filter(v) then a[#a+1]=v end end return a end)() )}
        else
            res = {table.unpack((function() local a={} for _,v in ipairs(res) do a[#a+1]=fn(v) end return a end)() )}
        end
    end
    return res
end
```

But that's too complex.

Better: Provide a simple pipeline that does filter then map in one pass.

Let's produce:

```lua
local function filterMap(list, filter, map)
    local out = {}
    for _, v in ipairs(list) do
        if filter(v) then out[#out+1] = map(v) end
    end
    return out
end

-- Usage:
-- local result = filterMap(players, function(p) return p:Alive() end, function(p) return p:Nick()


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output must be:

```lua
-- code
```
Reason: ...

But must be exactly one fenced code block, then exactly one line starting with Reason:. No extra text. The code block should contain the Lua code that shows the fastest typical way to loop a large sequential array-like table of numbers among pairs, ipairs, and numeric for. Probably we need to show three loops? Or show which is fastest? The user asks: "Show the fastest typical way to loop it among pairs, ipairs, and numeric for." So we need to present code that demonstrates the fastest typical way among those three methods. Probably numeric for is fastest. So we can show a numeric for loop as the fastest typical way. But they want to show among pairs, ipairs, and numeric for. So maybe we can show three loops and comment which is fastest. But they said "Show the fastest typical way to loop it among pairs, ipairs, and numeric for." So we need to show the fastest typical way, which is numeric for. So we can show a numeric for loop example. Possibly also mention that numeric for is fastest. But we must only output the code block and then Reason line. The code block can contain comments explaining. That's fine. Must be only Lua code inside the fence. Then after the fence, a line "Reason: ..." with short explanation. No extra text.

Thus output:

```lua
-- Assuming `arr` is a sequential array-like table
-- Numeric for is typically the fastest for sequential arrays
for i = 1, #arr do
    local v = arr[i]
    -- do something with v
end
```
Reason: Numeric for uses a simple integer index and avoids function calls, making it the fastest typical iteration method.

But we must ensure there is exactly one line starting with "Reason:". The line must be after the code fence, not inside. So we need to close the fence, then a newline, then "Reason: ..." line. No extra text. Ensure no extra blank lines? Probably okay to have a newline before Reason line. The instruction: "Return exactly one fenced lua code block, then exactly one line in the form Reason: <reason>." So after the fence, we need a line that starts with Reason:. So we can have a blank line before? That would be extra line not starting with Reason, which might violate "exactly one line in the form Reason:". It says exactly one line in the form Reason: <reason>. It doesn't forbid preceding blank lines? It says "exactly one line in the form Reason: <reason>." That suggests there should be exactly one line that matches that pattern, but there could be other lines? Probably they want only that line after the fence, no extra lines. Safer to have no extra blank lines. So after the fence, directly "Reason: ..." line. No extra blank lines before or after. So output:

```lua
-- Assuming `arr` is a sequential array-like table
-- Numeric for is typically the fastest for sequential arrays
for i = 1, #arr do
    local v = arr[i]
    -- do something with v
end
```
Reason: Numeric for uses a simple integer index and avoids function calls, making it the fastest typical iteration method.

But note that the code block includes triple backticks with lua, then code, then closing triple backticks. After that, we need a line starting with Reason:. The code block ends with ``` then newline then Reason line. That's fine.

Make sure there is no extra text before the fence. The entire visible reply must be: (1) one markdown code fence with language tag lua, containing only the requested Lua, (2) then exactly one line starting with Reason: and a short explanation. No other text before, between, or after.

Thus we must not have any extra text before the fence. So the reply starts with ```lua. Then code. Then ```. Then Reason line. No extra text before the fence. So the first characters of the reply must be ```lua. Good.

Now ensure the code block contains only the requested Lua. The request: "Show the fastest typical way to loop it among pairs, ipairs, and numeric for." So we need to show the fastest typical way among those three. So we can show a numeric for loop as the fastest. Possibly also show pairs and ipairs but they are slower. But the request is to show the fastest typical way among those. So we can just show the numeric for loop. That's fine.

Thus code block content:

-- Assuming `arr` is a sequential array-like table
-- Numeric for is typically the fastest


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output must be:

```lua
-- some fast debug line
```

Then a line: Reason: <reason>

We must not include any extra text. The code should be a faster alternative to print for debugging in Garry's Mod Lua. In GMod, print is relatively slow; you can use `Msg` or `print` is okay but faster is `print` vs `print`? Actually `print` writes to console but is slower; `Msg` writes to server console? In GMod, you can use `print` or `Msg` but for speed you can use `print` with `if 0 then` trick? Or use `print` with `if true then return end`? Hmm. The fastest is to use `print` is okay but you can use `print` with `if 0 then` to avoid overhead? Actually you can use `print` only when needed. But they ask "Show a faster alternative to print." In GMod, you can use `print` is slower; you can use `Msg` for console output? Actually `Msg` is similar to `print` but writes to the server console? In client side, you can use `print` or `Msg`. There's also `print` vs `print` is same. Maybe use `print` replaced with `print` but using `if 0 then` trick? Or use `print` with `if true then return end`? Not sure.

But we just need to provide a code snippet that shows a faster alternative. Could be:

```lua
if 0 then print("debug") end
```

But that's not faster; it's a trick to avoid parsing? Actually the Lua interpreter will skip the whole block if condition is false at compile time? In Lua, `if 0 then` is true? Actually 0 is falsey, so condition is false, so block is skipped. But the code is still parsed? Not sure.

Better: Use `print` replaced with `print` but using `if true then return end`? Hmm.

Maybe the answer: Use `print` replaced with `print` but using `print` is slower; use `print` with `if 0 then` to avoid overhead? Actually you can use `print` only when needed; but they want a faster alternative: use `print` replaced with `print` but using `print` is slower; use `print` with `if 0 then` to avoid overhead? Or use `print` with `if true then return end`? Not sure.

Simplify: Provide code:

```lua
if 0 then print("debug") end
```

But that's not a faster alternative; it's just a conditional that never runs. Actually you can use `print` replaced with `print` but using `print` is slower; you can use `print` with `if 0 then` to avoid parsing? Hmm.

Maybe they want to use `print` replaced with `print` but using `print` is slower; use `print` with `if 0 then` to avoid overhead? Actually the fastest way is to use `print` only when needed; but they ask to show a faster alternative to print. In GMod, you can use `print` but you can use `Msg` which is faster? Actually `Msg` is similar but maybe faster? Or you can use `print` with `if 0 then` to avoid overhead of printing? Not sure.

Better to give a snippet that uses `print` replaced with `print` but using `print` is slower; use `print` with `if 0 then` to avoid overhead? Actually you can use `print` replaced with `print` but using `print` is slower; you can use `print` with `if 0 then` to avoid overhead? I'm overthinking.

Probably they want something like:

```lua
if 0 then print("debug") end
```

But that's not a faster alternative; it's just a trick to conditionally compile out debug prints. Actually you can wrap debug prints in `if 0 then` to remove them in release builds, which is faster because they are never executed. So the faster alternative is to use conditional compilation: `if 0 then print("debug") end`. That way the code is stripped out by the compiler? In Lua, `if 0 then` is false, so the block is never executed, but still parsed? But it's cheap.

Thus we can provide that as the faster alternative.

We need exactly one fenced lua code block, containing only the requested Lua. So we must put the code inside the fence, nothing else. Then a line "Reason


```lua
-- Preferred idiomatic call
ply:SomeHelper()
```
Reason: Colon syntax is just syntactic sugar and has no measurable performance difference; it's the conventional style.


Answer must contain 0 through 1 candidate loops.

```lua
-- Sequential numeric array iterates faster than a string-keyed map
local seq = {1,2,3,4,5}
local map = {a=1,b=2,c=3,d=4,e=5}
-- iterate array (fast)
for i,v in ipairs(seq) do end
-- iterate map (slower)
for k,v in pairs(map) do end
```
Reason: Array iteration uses contiguous numeric keys and is optimized for speed.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Avoids constructing a Color object, which is faster in hot loops.


```lua
local db = sql.open("data.db")
local rows = db:query("SELECT * FROM players WHERE id = ?", {1})
```
Reason: SQLite is local, avoiding network latency.


```lua
local cachedPlayers = {}
local function UpdateCache()
    cachedPlayers = player.GetAll()
end
hook.Add("InitPostEntity", "CachePlayers", UpdateCache)
hook.Add("PlayerInitialSpawn", "CachePlayers", UpdateCache)
hook.Add("PlayerDisconnected", "CachePlayers", UpdateCache)

function GM:Think()
    for _, ply in ipairs(cachedPlayers) do
        -- example usage


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output should be:

```lua
-- code
```
Reason: ...

But must be exactly one fenced code block, then exactly one line starting with Reason:. No extra text. The code block must contain only the requested Lua code. The user wants a faster caching pattern for ply:SteamID() calls. So we need to show a caching pattern. Probably something like:

local steamIDCache = {}
local function getSteamID(ply)
    if not steamIDCache[ply] then
        steamIDCache[ply] = ply:SteamID()
    end
    return steamIDCache[ply]
end

But we need to show a pattern that caches per player, maybe using a table keyed by ply:UniqueID() or something. But the request: "In Garry's Mod Lua, a hot path calls ply:SteamID() repeatedly for the same players. Show a faster caching pattern." So we can provide a snippet that caches the result in a table using the player's SteamID as key? Actually we want to avoid calling SteamID repeatedly; we can store the result in a table keyed by the player object (or by some identifier). In GMod, player objects are not stable across frames? They might be, but we can use ply:SteamID() as key? Actually we want to cache the result for each player, maybe using a weak table. But simplest: local cache = {}; function GetSteamID(ply) if not cache[ply] then cache[ply] = ply:SteamID() end return cache[ply] end

But we need to show a pattern, maybe using a table with player as key, and using a metatable to clear when player disconnects. But the user only wants a faster caching pattern, not full implementation. So we can show something like:

local steamIDCache = {}
local function cachedSteamID(ply)
    local id = steamIDCache[ply]
    if id == nil then
        id = ply:SteamID()
        steamIDCache[ply] = id
    end
    return id
end

But we need to output only the Lua code inside the fence. Then a line "Reason: ..." after the fence. The code block must contain only the requested Lua. So we can put the snippet inside the fence. Then after the fence, a line "Reason: ..." with short explanation. No extra text. Ensure no extra whitespace before or after? The instruction: "Return exactly one fenced lua code block, then exactly one line in the form Reason: <reason>. No other text before, between, or after." So we must output:

```lua
-- code
```
Reason: ...

But the code block must be exactly one fenced code block. The fence must be markdown code fence with language tag lua. So we start with ```lua then code then ```. Then after that, a line starting with Reason: and then explanation. No extra text. So final output should be:

```lua
local cache = {}
local function cachedSteamID(ply)
    local id = cache[ply]
    if not id then
        id = ply:SteamID()
        cache[ply] = id
    end
    return id
end
```
Reason: Caches each player's SteamID once and reuses it, avoiding repeated expensive calls.

Make sure there is no extra text before the fence, after the fence besides the Reason line. The Reason line must be exactly one line, starting with "Reason: ". So we need to put that line after the closing fence. No extra blank lines? The instruction says "then exactly one line in the form Reason: <reason>." So after the fence, we need a line that starts with "Reason: " and then the reason. No extra lines. So we must not have a blank line between fence and Reason line? Probably it's okay to have a newline after the fence then the Reason line. That's fine. The Reason line must be exactly one line. So we can put it directly after the fence, maybe with a newline. So final output:

```lua
local cache = {}
local function cachedSteamID(ply)
    local id = cache[ply]
    if not id then
        id = ply:SteamID()
        cache[ply] = id
    end
    return id
end
```
Reason: Caches each player's SteamID once and reuses it, avoiding repeated expensive calls.

Check constraints: Only one fenced code block, then exactly one line starting with Reason:. No other text. The code block contains only the requested Lua. It includes a caching pattern. That's fine


```lua
local cache = {}
local function set(ply, k, v) cache[ply] = cache[ply] or {} cache[ply][k] = v end
local function get(ply, k) return cache[ply


```lua
local t = {}
for i = 1, 10000 do
    t[#t + 1] = "piece" .. i
end
local big = table.concat(t)
```
Reason: Using a table to collect pieces and table.concat is faster than repeated .. concatenation.


```lua
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(x, y, w, h)
```
Reason: Uses surface.DrawRect which skips rounding calculations and is slightly faster.


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with "Reason: " and a short explanation. No other text before, between, or after. So output must be:

```lua
-- code here
```

Then a line: Reason: <reason>

We must not include any extra text. The code should show a faster drawing approach among surface.* text helpers and draw.DrawText / SimpleTextOutlined. Probably we can show using surface.CreateFont and surface.SetTextColor and surface.DrawText? But they ask to show a faster drawing approach among surface.* text helpers and draw.DrawText / SimpleTextOutlined. So we can show using surface.CreateFont and surface.SetText and surface.DrawText? Actually surface.* helpers are faster than draw.DrawText? The fastest is using surface.CreateFont and surface.SetText and surface.DrawText? Or using surface.SetFont and surface.DrawText? In GMod, surface.DrawText is slower? The fastest is using surface.CreateFont once and then surface.SetFont and surface.DrawText each frame? Or using surface.SetText and surface.DrawText? Actually surface.DrawText draws the text using the current font; you can set the font via surface.SetFont. That's faster than draw.DrawText which uses a surface? I think surface.* helpers are faster. So we can show using surface.CreateFont outside the loop and then inside the loop use surface.SetFont and surface.SetTextColor and surface.DrawText.

We need to show a single-line string drawn each frame. So code could be:

local surface = surface
local surfaceCreateFont = surface.CreateFont
local font = surface.CreateFont("MyFont", "Arial", 24, 400, true, true, "")
hook.Add("HUDPaint", "FastDraw", function()
    surface.SetFont(font)
    surface.SetTextColor(255,255,255,255)
    surface.SetTextPos(10,10)
    surface.DrawText("Hello")
end)

But they want a faster drawing approach among surface.* text helpers and draw.DrawText / SimpleTextOutlined. So we can show using surface.CreateFont and surface.DrawText? Actually surface.DrawText is a helper that draws text using current font; but you can also use surface.SetText and surface.DrawText? In GMod, you can use surface.SetText and surface.DrawText to draw text at current position? Actually you set text via surface.SetText(string) then surface.DrawText() draws it at current position? I think you need to set text position via surface.SetPos? Actually there is surface.SetText, surface.SetTextPos? Let's recall: In GMod, you can use surface.SetFont, surface.SetTextColor, surface.SetTextPos, surface.DrawText. Or you can use surface.DrawText directly with a string? I think surface.DrawText draws the text at the current position set by surface.SetTextPos. There is also surface.DrawRect etc. But anyway.

Simplify: Use surface.CreateFont once, then in HUDPaint use surface.SetFont, surface.SetTextColor, surface.SetTextPos, surface.DrawText. That's faster than draw.DrawText which creates a new surface each frame? Actually draw.DrawText draws text using a temporary surface and is slower.

Thus code:

```lua
local font = surface.CreateFont("FastFont", "Arial", 24, 400, true, true, "")
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(font)
    surface.SetTextColor(255,255,255,255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello")
end)
```

That's a single line string drawn each frame. That's the faster approach.

Now after code fence, we need exactly one line: Reason: <reason>. Provide short explanation. Something like "Reason: Using surface.CreateFont and surface.DrawText avoids the overhead of draw.DrawText and SimpleTextOutlined, making it faster."

Make sure no extra spaces? The format: Reason: <reason>. So "Reason: Using surface.* helpers is faster than draw.DrawText / SimpleTextOutlined." That's fine.

Make sure there is exactly one line after the code fence, no extra blank lines. The code fence must be closed with triple backticks and language tag lua. Then newline, then Reason line.

No extra text before or after. So final output:

```lua
local font = surface.CreateFont("FastFont", "Arial", 24, 400, true, true, "")
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont(font)
    surface.SetTextColor(255,255,255,255)
    surface.SetTextPos(10


```lua
print(#t)  -- length of sequential array-like table
```
Reason: The # operator returns the length of a sequential array-like table.


```lua
local lookup = {a=true, b=true, c=true}
if lookup[item] then print("found") end
```
Reason: Using a hash table gives O(1) lookup instead of O(n) linear search.


```lua
local function fastRandom(t)
    return t[math.random(#t)]
end
```
Reason: Uses math.random to index directly, avoiding overhead of table.Random.


```lua
local t = {a = 1, b = 2, c = 3}
```
Reason: Using the constructor avoids extra assignments and is more concise.


We need to output exactly one markdown code fence with language tag lua, containing only the requested Lua code. Then exactly one line starting with Reason: and a short explanation. No other text before, between, or after. So output must be:

```lua
-- code? The user wants to show the generally faster approach between table.Empty(t) and t = {}.
-- Probably they want to show code that discards contents of a large sequential table often. The faster approach is t = {}? Or table.Empty(t)? Let's think.

In Garry's Mod Lua, table.Empty(t) clears the table by setting its length to 0? Actually table.Empty(t) sets the table to empty by setting its __len to 0? I recall that table.Empty(t) clears the table by setting its length to 0 and removing any keys? Actually table.Empty(t) sets the table to empty by setting its length to 0 and removing any keys? Let's recall: In GMod, table.Empty(t) empties a table by setting its length to 0 and removing any keys? Actually table.Empty(t) sets the table to empty by setting its length to 0 and removing any keys? I think it just sets the table to empty by setting its length to 0 and removing any keys? But the faster approach is t = {} because it just reassigns reference, which is O(1). table.Empty(t) iterates over the table to clear it, which is O(n). So the faster approach is t = {}.

Thus we need to show the generally faster approach between table.Empty(t) and t = {}. Probably they want to show code that discards contents of a large sequential table often. So we can show something like:

local t = {}
-- later when you want to discard:
t = {}  -- faster

Or maybe they want to show both and comment which is faster. But they said "Show the generally faster approach between table.Empty(t) and t = {}." So we need to show the faster approach. So we can show code that uses t = {} and maybe comment that it's faster. But we must only contain the requested Lua code. The user wants "Show the generally faster approach between table.Empty(t) and t = {}." So we can output a code block that demonstrates the faster approach, maybe with a comment. The code block should contain only the requested Lua. It can be something like:

```lua
-- Faster way to clear a large sequential table
t = {}  -- reassign reference, O(1) instead of iterating
```

But they said "Show the generally faster approach between table.Empty(t) and t = {}." So maybe they want to show code that uses t = {} as the faster approach. So we can output:

```lua
-- Use reassignment for speed
t = {}
```

That's it. Then after the code fence, we need exactly one line starting with Reason: and a short explanation. So after the fence we need a line "Reason: ..." with short explanation. No extra text. So final output must be:

```lua
-- Use reassignment for speed
t = {}
```
Reason: Reassigning the variable is O(1) while table.Empty iterates over all entries.

But we must ensure there is exactly one line starting with Reason: after the fence. The line must be exactly "Reason: <reason>" with no extra spaces? It says "exactly one line in the form Reason: <reason>." So we can have "Reason: Reassigning the variable is O(1) while table.Empty iterates over all entries." That's fine.

We must not have any extra text before, between, or after. So the entire output is:

```lua
-- Use reassignment for speed
t = {}
```
Reason: Reassigning the variable is O(1) while table.Empty iterates over all entries.

But note that there is a blank line between the fence and the Reason line? The instruction: "Return exactly one fenced lua code block, then exactly one line in the form Reason: <reason>." It doesn't forbid a blank line? It says "then exactly one line in the form Reason: <reason>." It likely expects the Reason line immediately after the fence, maybe with a newline. But we can have a newline after the fence, then the Reason line. That's okay. But we must not have any extra text before, between, or after. The fence block ends with ``` then newline, then Reason line. That's fine.

But we must ensure there is no extra text after the Reason line. So final output ends after that line.

Check: The code block must be exactly one fenced lua code block, containing only the requested Lua. The code block can contain comments and code. That's fine. Then after the fence, exactly one line starting with Reason:. So we must not have any extra lines after that


```lua
x = x * x
```
Reason: Multiplication is faster than exponentiation or pow.


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

```lua
for _, ply in ipairs(player.GetAll()) do
    print(ply:Nick())
end
```
Reason: Uses ipairs to iterate over all connected players.


```lua
if IsValid(ent) then
    -- ent is safe to use
end
Reason: IsValid returns false for nil or removed entities, preventing errors when calling methods.
```


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
Reason: Registers a Think hook callback identified as MyAddon.Think.
```


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    print(ent)
end
Reason: Using ents.FindByClass directly iterates over matching entities without constructing a full map entity table.
```


```lua
net.Receive("MyAddon.Sync", function(len)
    -- handle incoming data
end)
Reason: Registers a net.Receive handler for MyAddon.Sync to process incoming messages.
```


```lua
local myaddon_color = Color(255,0,0)
local val = myaddon_color
```
Reason: Flat locals avoid table lookups and are faster.


```lua
-- Preferred way to get a player's job name in DarkRP
local jobName = ply:getDarkRPVar("job") -- returns the job name as a string
-- Optionally, get the full job table for additional data
local jobTable = ply:getJobTable()
if jobTable then
    jobName = jobTable.name
end
```
Reason: getDarkRPVar is the official DarkRP API for job data and is more reliable than using GetNWString.


```lua
-- Example threshold check using squared distance
local thresholdSqr = myThreshold * myThreshold
if pos1:DistToSqr(pos2) < thresholdSqr then
    -- within threshold
end
```
Reason: Using DistToSqr avoids the costly square root of Distance, making threshold checks faster.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- Perform actions on each entity here
end
```
Reason: Using ipairs on ents.GetAll() is the wiki-recommended efficient way to iterate over all entities in Garry's Mod.


```lua
local function GetPlayersInSphere(pos, radius)
    local r2 = radius * radius
    local result = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= r2 then
            table.insert(result, ply)
        end
    end
    return result
end
```
Reason: Iterates only over players, avoiding the overhead of scanning all entities with ents.FindInSphere.


```lua
-- Pre‑allocate a zero Angle outside the hot loop
local zeroAngle = Angle()

-- Inside the hot path, reuse it by resetting its components
zeroAngle:Set(0, 0, 0)
-- now use zeroAngle as needed
```
Reason: Reusing a pre‑allocated Angle and resetting it with :Set avoids allocating a new userdata each call, which is faster in tight loops.


```lua
for i = 1, n do
    -- body
end
Reason: The numeric for loop is compiled to a single internal loop and is generally faster than a while loop for counting.
```


```lua
local ply = Entity(1) -- replace with actual player reference
local radius = 256
local nearby = ents.FindInSphere(ply:GetPos(), radius)
for _, ent in ipairs(nearby) do
    -- process ent
end
```
Reason: ents.FindInSphere is a highly optimized built‑in that quickly returns entities within a radius, making it faster than alternatives like FindInPVS for cheap spatial queries.


```lua
-- Faster: call hook.Run once with all players
hook.Run("MyCustomTick", player.GetAll())

-- Slower: loop and call hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("MyCustomTick", ply)
end
```
Reason: Calling hook.Run once with all players reduces hook invocation overhead, avoiding repeated function calls per player each tick.


```lua
hook.Add("HUDPaint", "OptimizedHealthHUD", function()
    local hp = LocalPlayer():Health()
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, Color(255,255,255))
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 30, Color(255,0,0))
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 50, Color(0,255,0))
end)
```
Reason: Caching the health value in a local variable avoids three separate function calls per frame, reducing overhead.


```lua
local lp = LocalPlayer()
-- Use lp wherever you need the player entity
lp:ChatPrint("Cached LocalPlayer example")
```
Reason: Caching LocalPlayer() in a local variable eliminates repeated global lookups, reducing overhead each frame.


```lua
local function PlayersFacingEachOther(ply1, ply2)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    return aim1:Dot(aim2) < -0.5 -- threshold for "roughly opposite"
end
```
Reason: Using the dot product of aim vectors avoids the expensive acos; a dot near -1 means the vectors point opposite, indicating the players are roughly looking at each other.


```lua
SomeHelper(ply)
```
Reason: SomeHelper(ply) avoids the extra table lookup involved in colon syntax, making it slightly faster.


```lua
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: numeric for loop avoids iterator overhead, making it fastest for large sequential tables.


```lua
local function pipeline(list, mapFn, filterFn)
    local out = {}
    for i = 1, #list do
        local v = list[i]
        if filterFn(v) then
            out[#out + 1] = mapFn(v)
        end
    end
    return out
end

-- Example usage:
local players = player.GetAll()
local aliveNames = pipeline(players,
    function(p) return p:Nick() end,
    function(p) return p:Alive() end)
```
Reason: This does map and filter in a single pass, avoiding intermediate allocations and extra function call overhead of DarkRP's fn combinators.


```lua
local cachedPlayers = {}

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

hook.Add("PlayerInitialSpawn", "CachePlayersRefresh", refreshPlayers)
hook.Add("PlayerDisconnect", "CachePlayersRefresh", refreshPlayers)

-- Example Think hook using the cached table
hook.Add("Think", "CachedPlayerThink", function()
    for _, ply in ipairs(cachedPlayers) do
        if IsValid(ply) then
            -- put your per‑player logic here
        end
    end
end)
```
Reason: Caches the player list and updates it only on join/leave events, avoiding costly ipairs(player.GetAll()) each tick.


```lua
Msg("DEBUG: ", value, "\n")
Reason: Msg writes directly to the console avoiding the formatting overhead of print, making it faster for hot‑path debugging.
```


```lua
local PlayerData = setmetatable({}, { __mode = "k" })
PlayerData[ply] = value   -- store
local val = PlayerData[ply] -- read
```
Reason: Plain table lookups avoid the entity's metatable __index overhead, making reads faster than accessing ply.someField.


```lua
-- Faster iteration: sequential numeric array
local values = { 10, 20, 30, 40 }
for i = 1, #values do
    local v = values[i]
    -- do something with v
end
```
Reason: Sequential number-indexed arrays allow direct index access without hash lookups, making iteration faster than string-keyed maps.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate r, g, b, a numbers avoids allocating a Color object each frame, reducing GC overhead and improving performance in hot draw paths.


```lua
local result = sql.Query("SELECT * FROM players WHERE steamid = '" .. sql.SQLStr(steamid) .. "'")
```
Reason: Local SQLite runs on the same machine as the server, eliminating network round‑trip overhead and thus provides lower latency for reads/writes compared to a remote MySQL database.


```lua
local steamIDCache = setmetatable({}, { __mode = "k" }) -- weak keys to avoid memory leak

local function GetSteamID(ply)
    if not IsValid(ply) then return "BOT" end
    local cached = steamIDCache[ply]
    if cached ~= nil then
        return cached
    end
    local id = ply:SteamID()
    steamIDCache[ply] = id
    return id
end
```
Reason: Caches each player's SteamID in a weak-key table, eliminating repeated costly calls to ply:SteamID().


```lua
-- Assuming `pieces` is a table containing thousands of small strings
local result = table.concat(pieces)
```
Reason: table.concat builds the final string in a single allocation, which is far faster than repeated .. concatenation that creates many intermediate strings.


```lua
surface.SetDrawColor(color.r, color.g, color.b, color.a)
surface.DrawRect(x, y, w, h)
```
Reason: surface.DrawRect skips the rounding checks and extra function calls of draw.RoundedBox(0, …), giving a faster draw for plain rectangles.


```lua
hook.Add("HUDPaint", "FastText", function()
    surface.SetFont("DermaDefault")
    surface.SetTextColor(255, 255, 255, 255)
    surface.SetTextPos(10, 10)
    surface.DrawText("Hello World")
end)
```
Reason: surface.SetFont + surface.DrawText skips the extra table handling and outline logic of draw.DrawText/SimpleTextOutlined, resulting in lower per‑frame overhead.


```lua
table.Empty(t)
```
Reason: table.Empty(t) empties the table in place without allocating a new table, reducing garbage collection overhead and being faster for large sequential tables.


```lua
-- Faster set membership test using a table as a hash set
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["cherry"] = true
}

local function contains(value)
    return mySet[value] ~= nil
end

-- Example usage
if contains("banana") then
    print("Found")
end
```
Reason: Using a table as a set gives O(1) key lookup instead of O(n) linear scan like table.HasValue.


```lua
local t = {x = 1, y = 2, z = 3}
```
Reason: The table constructor directly creates the table with fields in one step, avoiding extra hash lookups and assignments that occur when adding fields after an empty table.


```lua
local function randomSequential(t)
    return t[math.random(#t)]
end
```
Reason: Direct indexing with math.random is O(1) and skips the overhead of table.Random's safety checks and iteration.


```lua
local length = #myTable
```
Reason: The # length operator returns the count of consecutive integer keys starting at 1 in a sequence-like table.


```lua
local xx = x
for i = 1, 1000000 do
    local sq = xx * xx
    -- use sq as needed
end
```
Reason: Localizing the value avoids global lookups and multiplication is the fastest operation for squaring a number in Lua.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
Reason: Iterates over all connected players using ipairs for ordered traversal.
```


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Your code here
    print(ent)
end
```
Reason: Using ents.FindByClass directly retrieves only prop_physics entities without creating a table of all map entities.


```lua
net.Receive("MyAddon.Sync", function(len)
    -- Example: read a string sent from the server
    local message = net.ReadString()
    print("Received MyAddon.Sync:", message)
    -- Add custom handling logic here
end)
```
Reason: Registers a net.Receive handler for the MyAddon.Sync message to process incoming data.


HTTP request exceeded the attempt timeout.


Skipped: free model produced no text earlier in this run (will quarantine after run if pattern holds).


```lua
local myaddon_color = Color(255,0,0)
local col = myaddon_color
```
Reason: Flat local variables avoid table lookup overhead and are faster for frequent reads.


```lua
local zeroAngle = Angle(0,0,0) -- pre‑created zero angle
-- In hot path:
local ang = zeroAngle:Copy()   -- fresh zeroed angle without calling Angle() constructor
```
Reason: Reusing a pre‑allocated zero angle and copying it avoids the overhead of calling the Angle constructor each time.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your Think logic here
end)
```
Reason: Registers a Think hook callback with the unique identifier "MyAddon.Think" so it runs every frame.


```lua
if IsValid(ent) then
    -- safe to call methods on ent
end
```
Reason: Use IsValid to verify the entity is still valid before calling methods.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming MyAddon.Sync net message here
end)
```
Reason: Registers a net message handler for MyAddon.Sync using net.Receive.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- process ent
    end
end
```
Reason: Uses ents.Iterator to iterate entities without creating a full table.


```lua
-- Slow: new allocation each call
local function SlowZeroAngle()
    return Angle(0, 0, 0) -- or Angle()
end

-- Fast: reuse a single Angle instance
local _zeroAng = Angle(0, 0, 0)
local function FastZeroAngle()
    _zeroAng.p = 0
    _zeroAng.y = 0
    _zeroAng.r = 0
    return _zeroAng
end

-- Usage in hot path
for i = 1, 100000 do
    local ang = FastZeroAngle()
    -- use ang
end
```
Reason: Reusing a pre-allocated Angle avoids garbage collection pressure and allocation overhead in hot paths.


```lua
-- Preferred: flat local variable
local myAddonColor = Color(255, 0, 0)

-- Frequent read
local c = myAddonColor
```
Reason: Local variable access is a single register lookup, avoiding table traversals and global environment lookups, making it fastest for frequent reads.


```lua
local threshold = 100
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- vectors are within the threshold distance
end
```
Reason: DistToSqr returns the squared distance, allowing a fast threshold check without the costly square root.


```lua
-- Preferred way to get a player's job name in DarkRP
local jobName = ply:getDarkRPVar("job")
-- If you need the full job table (e.g., for salary, model, etc.)
local jobTable = ply:getJobTable()
local jobNameFromTable = jobTable and jobTable.name or "Unemployed"
```

Reason: DarkRP provides `getDarkRPVar("job")` and `getJobTable()` as the official, optimized APIs for accessing job information, avoiding direct reliance on generic networked strings.


```lua
for _, ent in ipairs(ents.GetAll()) do
    -- Your code here
end
```
Reason: Using ents.GetAll() with ipairs is the wiki-recommended efficient way to iterate over all entities in Garry's Mod.


OpenRouter error: Upstream error from Nvidia: ResourceExhausted: Worker local total request limit reached (32/32) (code 502)


```lua
-- Fast spatial query: find entities within a radius of a player
local function GetNearbyEntities(ply, radius)
    if not IsValid(ply) then return {} end
    local pos = ply:GetPos()
    return ents.FindInSphere(pos, radius)
end

-- Example usage
hook.Add("Think", "NearbyEntitiesExample", function()
    for _, ply in ipairs(player.GetAll()) do
        local nearby = GetNearbyEntities(ply, 500)
        -- Process nearby entities
    end
end)
```
Reason: ents.FindInSphere is highly optimized in the engine for radius-based spatial queries and outperforms FindInPVS in typical benchmarks.


```lua
-- Faster approach: iterate over all players and check distance squared
local function GetPlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local result = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:GetPos():DistToSqr(pos) <= radiusSqr then
            table.insert(result, ply)
        end
    end
    return result
end
```
Reason: Iterating player.GetAll() avoids scanning all entities and uses squared distance for faster checks.


```lua
-- Faster: single hook.Run with a table of all players
local function NotifyAllPlayersFast(data)
    local plys = player.GetAll()
    -- Pass the whole player list as a single argument
    hook.Run("CustomNotify", plys, data)
end

-- Slower: hook.Run per player (avoid this in tick-heavy code)
local function NotifyAllPlayersSlow(data)
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("CustomNotify", ply, data)
    end
end
```
Reason: Calling hook.Run once with a table of players reduces function call overhead and lets the hook system process the batch in a single dispatch, which is significantly faster in a per-tick context.


```lua
hook.Add("HUDPaint", "DrawHealthOptimized", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end
    local hp = ply:Health()
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, color_white)
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, color_white)
    draw.SimpleText("Life: " .. hp, "DermaDefault", 10, 50, color_white)
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids three redundant method calls per frame.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```
Reason: Caching math.sin in a local variable avoids global table lookups each iteration, improving performance in hot loops.


```lua
local cachedPlayer = NULL
hook.Add("Think", "CacheLocalPlayer", function()
    cachedPlayer = LocalPlayer()
end)

-- Use cachedPlayer instead of calling LocalPlayer() repeatedly
```
Reason: Caching the LocalPlayer entity in a Think hook eliminates repeated global lookups and function calls, improving performance.


```lua
-- Fastest: avoid Color constructor entirely
hook.Add("HUDPaint", "FastPaint", function()
    surface.SetDrawColor(255, 255, 255, 255) -- direct RGBA, no allocation
    surface.DrawRect(0, 0, 100, 100)
end)

-- If you need a reusable color object, create it once outside the hook
local white = Color(255, 255, 255, 255)
hook.Add("HUDPaint", "CachedPaint", function()
    surface.SetDrawColor(white)
    surface.DrawRect(0, 0, 100, 100)
end)
```
Reason: Creating a new Color object every frame allocates garbage; using surface.SetDrawColor with raw numbers or a cached Color eliminates per-frame allocations.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- roughly cos(45°)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local dir12 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local dir21 = -dir12
    return aim1:Dot(dir12) > threshold and aim2:Dot(dir21) > threshold
end
```
Reason: Uses dot products of aim vectors with normalized direction vectors to avoid expensive acos calls, providing a cheap "looking at each other" test.


```lua
-- Faster console output in a hot path: use Msg instead of print
Msg("Debug: " .. tostring(myVar) .. "\n")
```
Reason: Msg writes directly to the console without the extra formatting and newline handling that print performs, making it significantly faster in tight loops.


```lua
SomeHelper(ply)
```
Reason: Direct function call avoids metatable lookup and is slightly faster.


```lua
local t = { ... } -- large sequential array of numbers
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: Numeric for loop is fastest because it uses direct index access without iterator function overhead, and LuaJIT optimizes it heavily.


```lua
-- Cache for the current player list
local cachedPlayers = {}

-- Helper to rebuild the cache
local function RefreshPlayerCache()
    cachedPlayers = player.GetAll()
end

-- Initial population
RefreshPlayerCache()

-- Update cache when a player fully joins
hook.Add("PlayerInitialSpawn", "UpdatePlayerCache_Join", function(ply)
    RefreshPlayerCache()
end)

-- Update cache when a player leaves
hook.Add("PlayerDisconnected", "UpdatePlayerCache_Leave", function(ply)
    RefreshPlayerCache()
end)

-- Example Think/Tick hook using the cached table
hook.Add("Think", "MyOptimizedThink", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Your per‑player logic here
    end
end)
```
Reason: Caches the player list and only refreshes on join/leave events, avoiding ipairs(player.GetAll()) every tick.


Answer must contain 0 through 2 candidate loops.

```lua
-- Fast list pipeline without DarkRP's fn library
local function pipeline(tbl, ...)
    local ops = {...}
    local out = tbl
    for _, op in ipairs(ops) do
        local typ, fn = op[1], op[2]
        local nxt = {}
        if typ == "filter" then
            for i = 1, #out do
                local v = out[i]
                if fn(v) then nxt[#nxt + 1] = v end
            end
        elseif typ == "map" then
            for i = 1, #out do
                nxt[#nxt + 1] = fn(out[i])
            end
        else
            error("unknown op " .. tostring(typ))
        end
        out = nxt
    end
    return out
end

-- Example usage
local data = {1,2,3,4,5,6,7,8,9,10}
local result = pipeline(data,
    {"filter", function(x) return x % 2 == 0 end},
    {"map",    function(x) return x * 2 end},
    {"filter", function(x) return x > 10 end}
)
-- result == {12, 14, 16, 18, 20}
```

Reason: Plain loops avoid the overhead of fn's function‑currying and table allocations, giving a measurable speed boost for typical DarkRP list processing.


```lua
-- Initialize a dedicated storage table for the player (once)
if not ply._tempData then ply._tempData = {} end

-- Cache the table locally for the current scope
local data = ply._tempData

-- Fast write
data.someField = value

-- Fast read
local val = data.someField
```

Reason: Using a dedicated per-player table (ply._tempData) and a local reference avoids repeated entity metatable lookups, giving faster direct table access for frequent reads/writes.


```lua
-- Sequential array (fast iteration)
local arr = { "a", "b", "c", "d" }
for i = 1, #arr do
    local v = arr[i]
    -- process v
end

-- String-keyed map (slower iteration)
local map = { foo = 1, bar = 2, baz = 3 }
for k, v in pairs(map) do
    -- process k, v
end
```
Reason: Sequential arrays with integer keys 1..n allow O(1) indexed access and are optimized by LuaJIT, while string-keyed maps require hash lookups and pairs iteration overhead.


```lua
surface.SetDrawColor(255, 0, 0, 255)
```
Reason: Passing separate r,g,b,a numbers avoids Color object allocation and table lookups, making it faster in hot draw paths.


```lua
-- Simple query using Garry's Mod built-in SQLite (sql library)
local steamid = "STEAM_0:1:123456"
local query = "SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid)
local result = sql.Query(query)
if result then
    -- handle result rows
    for _, row in ipairs(result) do
        print(row.key, row.value)
    end
end
```
Reason: Local SQLite runs in-process with no network round‑trip, giving lower latency for a single server.


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

local function GetSteamID(ply)
    local cached = steamIDCache[ply]
    if cached then return cached end
    local sid = ply:SteamID()
    steamIDCache[ply] = sid
    return sid
end

-- Example hot‑path usage
hook.Add("Think", "ExampleHotPath", function()
    for _, ply in ipairs(player.GetAll()) do
        local sid = GetSteamID(ply)
        -- use sid ...
    end
end)
```
Reason: Caching SteamID results in a weak‑keyed table eliminates repeated calls to the relatively expensive ply:SteamID() method while allowing garbage collection of disconnected players.


```lua
-- Fast string building in Garry's Mod using a table buffer
local buffer = {}
local insert = table.insert

-- Simulate thousands of small pieces
for i = 1, 10000 do
    insert(buffer, "piece" .. i)
end

-- Single concatenation at the end
local bigString = table.concat(buffer)
```

Reason: Using a table to collect pieces and a single table.concat avoids the O(n²) cost of repeated .. concatenation.


```lua
-- Fastest single-line text drawing per frame
local font = "DermaDefault"
local text = "Hello, World!"
local x, y = 100, 100
local color = Color(255, 255, 255, 255)

hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont(font)
    surface.SetTextColor(color.r, color.g, color.b, color.a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: surface.DrawText bypasses the draw library's extra function calls and outline rendering, giving the lowest per-frame overhead for static single-line text.


```lua
-- Directly use surface.DrawRect for non-rounded rectangles (avoids draw.RoundedBox overhead)
local function DrawRectFast(x, y, w, h, col)
    surface.SetDrawColor(col.r, col.g, col.b, col.a)
    surface.DrawRect(x, y, w, h)
end

-- Usage example:
-- DrawRectFast(10, 10, 100, 50, Color(255, 0, 0, 255))
```
Reason: Using surface.DrawRect directly avoids the overhead of draw.RoundedBox's radius check and function call, yielding a small performance gain for many rectangles per frame.


```lua
local len = #myArray
```
Reason: The `#` operator is the standard way to get the length of a sequential array-like table in Lua (and Garry's Mod).


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

local function hasValue(set, val)
    return set[val] ~= nil
end

-- Example usage
print(hasValue(mySet, "value2")) -- true
print(hasValue(mySet, "missing")) -- false
```
Reason: A hash set (table with values as keys) gives O(1) average lookup, while table.HasValue scans the list O(n).


```lua
t = {}
```
Reason: t = {} is faster because it avoids iterating over the table and simply allocates a new empty table, which is cheaper for large sequential tables in LuaJIT.


```lua
local function fastRandom(tbl)
    return tbl[math.random(#tbl)]
end
```
Reason: Using math.random with the length operator (#tbl) directly indexes the sequential table, avoiding table.Random's internal iteration and counting overhead.


```lua
-- Faster: use a table constructor to create the table with known fields in one step
local myTable = { name = "example", value = 42, enabled = true }
```
Reason: Table constructors allocate and initialize all fields in a single operation, avoiding the overhead of multiple separate assignments.


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

Reason: Using multiplication (x * x) avoids the overhead of the exponentiation operator (^) which calls a metamethod or C function, making it faster in tight loops.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- code for each player
end
```
Reason: Using ipairs for efficient sequential iteration over the table returned by player.GetAll().


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- process prop_physics entity
    end
end
```
Reason: ents.Iterator() yields entities one by one without building a table of all entities.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your Think logic here
end)
```
Reason: Registers a function to run every frame using the Think hook with the unique identifier MyAddon.Think.


```lua
if IsValid(ent) then
    -- ent is safe to use
end
```
Reason: IsValid checks if the entity exists and is not marked for removal, preventing errors when calling methods on invalid entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming MyAddon.Sync net message
    local data = net.ReadTable() -- Example: read a table sent by the client
    -- Process 'data' as needed
end)
```
Reason: Registers a server‑side net message handler for the custom message "MyAddon.Sync".


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

-- frequent read
local c = myAddonColor
```
Reason: Local variable access avoids table lookups and is the fastest in Lua.


```lua
-- Preferred DarkRP API to get a player's job name
local jobName = ply:getDarkRPVar("job")

-- Alternative using team system (also acceptable)
-- local jobName = team.GetName(ply:Team())
```
Reason: getDarkRPVar is the official DarkRP accessor for job data, avoiding direct NWString usage.


```lua
local threshold = 100
if vec1:DistToSqr(vec2) < threshold * threshold then
    -- vectors are within the threshold distance
end
```
Reason: DistToSqr avoids the expensive square root by comparing squared distances directly.


```lua
-- Pre-allocate a single Angle once
local zeroAng = Angle(0, 0, 0)

-- Hot path: reuse and zero it without allocation
zeroAng.p = 0
zeroAng.y = 0
zeroAng.r = 0
-- Alternatively: zeroAng:Zero()
```

Reason: Reusing a pre‑allocated Angle and manually zeroing its components avoids the overhead of creating a new Angle object on every iteration.


```lua
-- Fast spatial query: find all entities within 500 units of the player
local ply = Entity(1) -- example player
local radius = 500
local nearbyEnts = ents.FindInSphere(ply:GetPos(), radius)

for _, ent in ipairs(nearbyEnts) do
    -- Process each nearby entity
    print(ent:GetClass())
end
```
Reason: ents.FindInSphere is a highly optimized engine function for radius-based proximity checks and consistently outperforms FindInPVS in benchmarks for local spatial queries.


```lua
for _, ent in ents.Iterator() do
    -- Perform actions on each entity
    -- Example: print(ent:GetClass())
end
```
Reason: Use ents.Iterator() as the wiki-recommended efficient iterator for visiting all entities without creating a temporary table.


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

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

    return playersInRange
end
```

Reason: Iterating over `player.GetAll()` checks only player entities and uses squared distance to avoid the overhead of `ents.FindInSphere` which scans all entities.


```lua
for i = 1, n do
    -- loop body
end
```
Reason: Numeric for loops are optimized in Lua and generally faster than while loops for simple counting.


```lua
hook.Add("HUDPaint", "DrawHealthOptimized", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end
    local hp = ply:Health()
    draw.SimpleText("Health: " .. hp, "DermaDefault", 10, 10, Color(255,255,255))
    draw.SimpleText("HP: " .. hp, "DermaDefault", 10, 30, Color(255,255,255))
    draw.SimpleText("Life: " .. hp, "DermaDefault", 10, 50, Color(255,255,255))
end)
```
Reason: Caching LocalPlayer():Health() in a local variable avoids three redundant method calls each frame.


```lua
-- Faster: single hook.Run with all players
local allPlayers = player.GetAll()
hook.Run("CustomTick", allPlayers)

-- Slower: loop and call hook.Run per player
-- for _, ply in ipairs(player.GetAll()) do
--     hook.Run("CustomTick", ply)
-- end
```
Reason: Calling hook.Run once avoids repeated function lookups and per-player overhead, reducing CPU usage each tick.


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

hook.Add("HUDPaint", "OptimizedPaint", function()
    surface.SetDrawColor(white)
    -- drawing code here
end)
```
Reason: Caching the Color object outside the paint hook prevents per-frame allocation and reduces garbage collection pressure.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local v = sin(i)
end
```
Reason: Caching math.sin in a local variable avoids global table lookups each iteration, improving performance in hot loops.


```lua
local function AreLookingAtEachOther(ply1, ply2, threshold)
    threshold = threshold or 0.7 -- roughly cos(45°)
    local aim1 = ply1:GetAimVector()
    local aim2 = ply2:GetAimVector()
    local dir12 = (ply2:GetPos() - ply1:GetPos()):GetNormalized()
    local dir21 = -dir12
    return aim1:Dot(dir12) > threshold and aim2:Dot(dir21) > threshold
end
```
Reason: Dot products give the cosine of the angle directly, avoiding expensive math.acos while still providing a fast “looking at each other” test.


```lua
SomeHelper(ply)
```
Reason: Direct function call avoids metatable lookup and extra argument handling, making it slightly faster than the method call syntax.


```lua
-- Cache LocalPlayer to avoid repeated global lookups
local LocalPlayerCache = nil

hook.Add("Think", "UpdateLocalPlayerCache", function()
    LocalPlayerCache = LocalPlayer()
end)

-- Example usage
local function MyFunction()
    local ply = LocalPlayerCache
    if not IsValid(ply) then return end
    -- use ply here
end
```
Reason: Caching LocalPlayer in a Think hook eliminates the overhead of calling the global function every time, giving faster access in frequently run code.


```lua
Msg("Debug: " .. someVariable)
```

Reason: Msg writes directly to the console without the overhead of print's argument processing and automatic newline.


```lua
local t = {1, 2, 3, 4, 5} -- large sequential array
for i = 1, #t do
    local v = t[i]
    -- process v
end
```
Reason: Numeric for loop directly indexes the table without iterator function calls, giving the best performance for sequential arrays.


```lua
local cachedPlayers = {}

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

-- Update cache when a player fully joins or leaves
hook.Add("PlayerInitialSpawn", "PlayerCache_Refresh", refreshPlayerCache)
hook.Add("PlayerDisconnected", "PlayerCache_Refresh", refreshPlayerCache)

-- Example Think/Tick hook using the cached table
hook.Add("Think", "MyThinkHook", function()
    for _, ply in ipairs(cachedPlayers) do
        -- Your per-player logic here
    end
end)
```
Reason: Caches the player list and only refreshes on join/leave events, avoiding ipairs(player.GetAll()) every tick.


```lua
-- Fast list pipeline without DarkRP's fn library
local function pipeline(tbl, ...)
    local ops = {...}
    local out = tbl
    for _, op in ipairs(ops) do
        local typ, fn = op[1], op[2]
        if typ == "filter" then
            local n = 0
            for i = 1, #out do
                local v = out[i]
                if fn(v) then
                    n = n + 1
                    out[n] = v
                end
            end
            -- truncate
            for i = n + 1, #out do out[i] = nil end
        elseif typ == "map" then
            for i = 1, #out do
                out[i] = fn(out[i])
            end
        else
            error("unknown op " .. tostring(typ))
        end
    end
    return out
end

-- Example usage:
local data = {1,2,3,4,5,6,7,8,9,10}
local result = pipeline(data,
    {"filter", function(x) return x % 2 == 0 end},
    {"map",    function(x) return x * 10 end}
)
-- result == {20,40,60,80,100}
```

Reason: Uses a single pass per operation with in‑place table mutation, avoiding the overhead of fn's function‑composition and temporary tables.


```lua
-- Fast iteration: sequential array
local arr = {"a", "b", "c"}
for i = 1, #arr do
    local v = arr[i]
    -- use v
end

-- Slow iteration: string-keyed map
local map = {foo = "a", bar = "b", baz = "c"}
for k, v in pairs(map) do
    -- use v
end
```
Reason: Sequential arrays with numeric indices allow O(1) indexed access and cache-friendly iteration, while string-keyed maps require hash lookups and pairs() traversal.


```lua
-- Fast SteamID cache for Garry's Mod
local steamIDCache = {}

-- Helper to get cached SteamID
local function GetSteamID(ply)
    if not IsValid(ply) then return "" end
    local cached = steamIDCache[ply]
    if cached then return cached end

    local sid = ply:SteamID()
    steamIDCache[ply] = sid
    return sid
end

-- Invalidate cache when a player disconnects
hook.Add("PlayerDisconnected", "ClearSteamIDCache", function(ply)
    steamIDCache[ply] = nil
end)

-- Example hot‑path usage
hook.Add("Think", "ExampleHotPath", function()
    for _, ply in ipairs(player.GetAll()) do
        local sid = GetSteamID(ply)
        -- use sid ...
    end
end)
```
Reason: Caches SteamID per player in a table, avoiding repeated calls to ply:SteamID() and clears entries on disconnect.


```lua
-- Fastest: pass raw numbers, avoid Color object allocation
surface.SetDrawColor(255, 0, 0, 255)
```

Reason: Passing r,g,b,a numbers directly avoids creating a temporary Color object, reducing GC pressure in hot draw loops.


```lua
-- Simple query using Garry's Mod built-in SQLite (sql library)
local steamid = "STEAM_0:1:123456"
local query = "SELECT * FROM player_data WHERE steamid = " .. sql.SQLStr(steamid)
local result = sql.Query(query)
if result then
    -- handle result rows
end
```
Reason: Local SQLite runs in-process with no network round‑trip, giving lower latency for a single server.


```lua
-- Fast per-player storage using a global table keyed by entity index
local playerData = {}

-- Store value
local function SetData(ply, key, value)
    local idx = ply:EntIndex()
    playerData[idx] = playerData[idx] or {}
    playerData[idx][key] = value
end

-- Retrieve value
local function GetData(ply, key)
    local idx = ply:EntIndex()
    local data = playerData[idx]
    return data and data[key]
end

-- Example usage
hook.Add("PlayerInitialSpawn", "InitTempData", function(ply)
    SetData(ply, "tempField", 0)
end)

hook.Add("Think", "ReadTempData", function()
    for _, ply in ipairs(player.GetAll()) do
        local val = GetData(ply, "tempField")
        -- use val
    end
end)
```
Reason: Using a global table keyed by EntIndex avoids entity metamethod overhead, making reads significantly faster than ply.someField = value.


```lua
surface.SetDrawColor(255, 0, 0, 255)
surface.DrawRect(100, 100, 200, 50)
```
Reason: surface.DrawRect bypasses the radius logic of draw.RoundedBox and is a direct, lower-overhead rectangle draw call.


```lua
local pieces = {}
for i = 1, 10000 do
    pieces[#pieces + 1] = "part" .. i
end
local bigString = table.concat(pieces)
```

Reason: Using a table to collect strings and a single table.concat avoids the O(n²) cost of repeated .. concatenation.


```lua
local len = #myArray
```
Reason: The `#` operator is the standard way to get the length of a sequential array-like table in Lua (and Garry's Mod).


```lua
-- Fast single-line text drawing using surface library
local fontName = "FastHUDFont"
local text = "Hello, Garry's Mod!"
local x, y = 100, 100
local col = Color(255, 255, 255, 255)

-- Create font once
surface.CreateFont(fontName, {
    font = "Roboto",
    size = 18,
    weight = 500,
    antialias = true,
})

hook.Add("HUDPaint", "FastTextDraw", function()
    surface.SetFont(fontName)
    surface.SetTextColor(col.r, col.g, col.b, col.a)
    surface.SetTextPos(x, y)
    surface.DrawText(text)
end)
```
Reason: surface.DrawText with a pre‑created font avoids the overhead of draw.DrawText and SimpleTextOutlined, which parse arguments and create temporary objects each frame.


```lua
-- Faster way to discard contents of a large sequential table
local t = {1, 2, 3, 4, 5}
-- ... later, to clear:
t = {}
```
Reason: Assigning a new empty table (t = {}) is generally faster than table.Empty(t) because it avoids iterating over all elements and simply creates a new table, leaving the old one for garbage collection.


```lua
-- Using a hash set for O(1) membership test
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["cherry"] = true
}

local function HasValueFast(set, val)
    return set[val] ~= nil
end

-- Example usage
print(HasValueFast(mySet, "banana")) -- true
print(HasValueFast(mySet, "durian")) -- false
```
Reason: A table used as a hash set gives O(1) lookup, while table.HasValue scans the list linearly (O(n)).


```lua
-- Faster: table constructor
local t = {field1 = 1, field2 = 2, field3 = 3}

-- Slower: assign fields after creation
local t2 = {}
t2.field1 = 1
t2.field2 = 2
t2.field3 = 3
```
Reason: The table constructor builds the table with all fields in a single allocation, avoiding repeated hash insertions.


```lua
local function fastRandom(tbl)
    return tbl[math.random(1, #tbl)]
end
```
Reason: Using math.random with the length operator avoids the overhead of table.Random's iteration and counting.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- code for each player
end
```
Reason: Using ipairs provides a clean sequential loop over the player table returned by player.GetAll().


```lua
for _, ent in ipairs(ents.GetAll()) do
    if ent:GetClass() == "prop_physics" then
        -- do something with ent
    end
end
```
Reason: Uses ents.GetAll() to iterate through all entities and filters for prop_physics class without pre-building a separate table.


```lua
local x = 10
local squared = x * x
```
Reason: Multiplication (x * x) is faster than the power operator (x^2) in Lua, especially in tight loops.


```lua
MyAddon = MyAddon or {}
MyAddon.Think = function()
    -- Your think logic here
end
hook.Add("Think", "MyAddon.Think", MyAddon.Think)
```
Reason: Registers a Think hook callback under the identifier MyAddon.Think for use in Garry's Mod.


```lua
if IsValid(ent) and not ent:IsDestroyable() then
    ent:SomeMethod()
end
```
Reason: IsValid checks if the entity exists and is not marked for deletion, preventing errors from calling methods on invalid entities.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming net message here
    local data = net.ReadString(len)
    print("Received MyAddon.Sync from", ply:SteamID(), "with data:", data)
end)
```
Reason: This registers a net message handler for "MyAddon.Sync" using Garry's Mod's net.Receive function, which is the standard way to listen for and process incoming network messages in Lua.


```lua
-- Faster: reuse a pre-zeroed Angle instead of creating new ones
local zeroAngle = Angle(0, 0, 0)

-- In hot path, use the cached zeroAngle directly
function GetZeroAngle()
    return zeroAngle
end

-- Or reset an existing Angle if you need to modify it
local tempAngle = Angle()
function GetZeroedAngle()
    tempAngle.p = 0
    tempAngle.y = 0
    tempAngle.r = 0
    return tempAngle
end
```

Reason: Reusing a pre-zeroed Angle or resetting an existing one avoids the overhead of garbage collection and memory allocation that occurs when creating new Angle objects in a hot path.


```lua
local color = myaddon.config.color
```

Reason: Local variables are faster than table lookups because they avoid the overhead of nested table access and global lookups.


```lua
ply:GetJob()
```
Reason: GetJob() is the preferred API to get a player's job name in DarkRP as it returns the job table directly, avoiding the unreliable NWString method.


```lua
local distanceSquared = (vector1 - vector2):LengthSqr()
if distanceSquared < threshold * threshold then
    -- within threshold
end
```
Reason: Using LengthSqr() avoids the expensive sqrt operation from Length() and is the preferred method for threshold distance comparisons in Garry's Mod Lua.


```lua
for _, entity in ipairs(ents.GetAll()) do
    -- Process each entity here
end
```
Reason: Uses ipairs with ents.GetAll() as recommended by the Garry's Mod wiki for efficient entity iteration.


```lua
-- Faster player radius check using player.GetAll() with squared distance optimization
local playerList = player.GetAll()
local pos = Vector(0, 0, 0) -- your center position
local radius = 500
local radiusSq = radius * radius
local playersInRadius = {}

for i = 1, #playerList do
    local ply = playerList[i]
    if IsValid(ply) then
        local distSq = ply:GetPos():DistToSqr(pos)
        if distSq <= radiusSq then
            table.insert(playersInRadius, ply)
        end
    end
end
```

Reason: Using player.GetAll() with squared distance comparison avoids the expensive entity iteration and sphere query overhead of ents.FindInSphere, providing faster player-specific radius checks.


```lua
local n = 1000
local i = 1
while i <= n do
    -- loop body
    i = i + 1
end
```
Reason: while loops with manual increment are generally faster in Garry's Mod Lua because they avoid the overhead of the for loop's iterator function and variable setup.


```lua
-- Faster pattern: single hook.Run with all players
hook.Add("Think", "NotifyAllPlayers", function()
    local players = player.GetAll()
    hook.Run("OnPlayerTickBatch", players)
end)

-- Slower pattern: loop and call hook.Run per player
hook.Add("Think", "NotifyEachPlayer", function()
    for _, ply in ipairs(player.GetAll()) do
        hook.Run("OnPlayerTick", ply)
    end
end)
```
Reason: Calling hook.Run once with all players avoids the overhead of multiple hook dispatches and table iterations per player, reducing CPU usage significantly in Garry's Mod's Lua environment.


```lua
hook.Add("HUDPaint", "FasterHealthDraw", function()
    local health = LocalPlayer():Health()
    -- Use health variable for three separate draw calls
    draw.RoundedBox(0, 100, 100, health, 20, color_green)
    draw.RoundedBox(0, 100, 130, health * 0.5, 20, color_yellow)
    draw.RoundedBox(0, 100, 160, health * 0.25, 20, color_red)
end)
```
Reason: Caching the health value in a local variable avoids redundant calls to LocalPlayer():Health() which can be expensive, especially if it involves network or table lookups.


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

hook.Add("Paint", "FasterWhite", function()
    draw.Color(white)
    -- drawing code here
end)
```
Reason: Pre-creating the Color object once outside the paint loop avoids repeated table allocations and function calls on every frame.