Performance Best Practices¶
Guide for optimizing code performance in FiveM resources.
Distance Calculations¶
❌ Slow - GTA Native:
local distance = GetDistanceBetweenCoords(coords.x, coords.y, coords.z, v.coords.x, v.coords.y, v.coords.z, true)
✅ Fast - FiveM Native:
The FiveM vector math is significantly faster and more readable.
Loop Optimization¶
Cache Frequently Used Values¶
❌ Bad:
for i = 1, #players do
local player = players[i]
local ped = GetPlayerPed(player)
local coords = GetEntityCoords(ped)
-- Using GetPlayerPed and GetEntityCoords repeatedly is expensive
end
✅ Good:
local playerPed = PlayerPedId()
local playerCoords = GetEntityCoords(playerPed)
for i = 1, #players do
local player = players[i]
-- Use cached values when possible
end
Use Citizen.Wait Wisely¶
❌ Bad:
Citizen.CreateThread(function()
while true do
Citizen.Wait(0) -- Runs every frame unnecessarily
-- Code that doesn't need to run every frame
end
end)
✅ Good:
Citizen.CreateThread(function()
while true do
Citizen.Wait(1000) -- Only run once per second
-- Code that checks states periodically
end
end)
Entity Checks¶
Local Player Checks¶
❌ Slow:
✅ Fast:
Entity Existence¶
❌ Slow:
✅ Fast:
Table Operations¶
Pre-allocate Tables¶
❌ Bad:
✅ Good:
Local Variable Access¶
❌ Slow:
✅ Fast:
Network Events¶
Batch Updates¶
❌ Bad:
✅ Good:
local batch = {}
for i = 1, 100 do
batch[#batch + 1] = i
end
TriggerServerEvent('updateItems', batch)
Use Statebags for Frequent Updates¶
❌ Bad:
✅ Good:
General Tips¶
- Avoid
pairs()for arrays - Use numericforloops with#tableinstead - Cache
GetEntityCoords()- Don't call it multiple times in the same frame - Use zone systems - Check proximity before doing expensive operations
- Profile your code - Use
profiler startandprofiler viewcommands - Minimize network traffic - Only send data that changed
- Use locals - Local variables are faster than globals
- Avoid string concatenation in loops - Use
table.concat()instead