fivemluaperformanceoptimization
Optimize Lua Performance in FiveM — Write code so the server doesn't lag.
March 22, 2026
1 min read
5 views
Optimize Lua Performance in FiveM
A good FiveM server must be able to run scripts without causing lag. Most problems come from inefficient Lua code.
Problem 1: Thread running every frame
-- Consumables: Runs 60 times/sec.
Citizen.CreateThread(function()
while true do
checkZones()
Citizen.Wait(0) -- BAD
end
end)
-- Better: Run 2 times/sec.
Citizen.CreateThread(function()
while true do
checkZones()
Citizen.Wait(500) -- GOOD
end
end)
-- Best: Dynamic wait
Citizen.CreateThread(function()
while true do
local nearZone = checkZones()
Citizen.Wait(nearZone and 100 or 1000)
end
end)
Problem 2: Spam MySQL Queries
-- Cache data instead of querying every time
local playerCache = {}
AddEventHandler('playerJoining', function()
local src = source
MySQL.Async.fetchAll('SELECT * FROM users WHERE identifier = @id', {
['@id'] = GetPlayerIdentifier(tostring(src), 0)
}, function(result)
playerCache[src] = result[1]
end)
end)
AddEventHandler('playerDropped', function()
playerCache[source] = nil
end)
Problem 3: Not using Local Variables
-- slower than: lookup every time
for i = 1, 10000 do
math.random()
end
-- 30% faster: cache local
local random = math.random
for i = 1, 10000 do
random()
end
Problem 4: Draw every frame without checking the distance.
Citizen.CreateThread(function()
while true do
local playerCoords = GetEntityCoords(PlayerPedId())
local targetCoords = vector3(100.0, 200.0, 30.0)
if GetDistanceBetweenCoords(playerCoords, targetCoords, true) <= 10.0 then
DrawText3D(100.0, 200.0, 30.0, "Press button")
Citizen.Wait(0) -- when near draw every frame
else
Citizen.Wait(500) -- far reduces poll
end
end
end)
Performance Checklist
- No Thread runs Wait(0) unnecessarily.
- MySQL queries are cached whenever possible.
- Use local variables for frequently used functions.
- Draw calls have a distance check first.
Summary
Lua performance optimization isn't difficult. Just know what's using up a lot of resources. Caching data, reducing poll frequency, and using local variables can have a big impact on performance.
Related Articles
Breaking: GTA Online อัพเดท "Money Fronts" — FiveM Server Owners ต้องทำอะไร?
Rockstar ปล่อย GTA Online อัพเดท Money Fronts มีผลกระทบต่อ FiveM servers บางส่วน นี่คือสิ่งที่ต้องทำทันทีหลังอัพเดท
Community Spotlight: Script และ Projects ที่น่าสนใจจาก FiveM Community
รวม scripts, tools และ projects ที่โดดเด่นจาก FiveM community ในช่วงที่ผ่านมา ตั้งแต่ free resources ถึง open-source projects
txAdmin อัพเดทใหม่ — Dashboard, Diagnostics และ Ban System ที่ดีขึ้น
txAdmin ซึ่งตอนนี้เป็นส่วนหนึ่งของ Cfx.re อย่างเป็นทางการ ได้รับการอัพเดทครั้งใหญ่ มี features ใหม่ที่ทำให้ Server Management ง่ายขึ้นมาก