Performance: MicroProfiler, memory, network

Profile a Roblox game with the MicroProfiler, Script Profiler and Developer Console. Find what Beacon Yard does every frame, profile a drill, count its particles, read memory and network, and measure native code before and after.

Tool lesson, about 95 minutes, 14 steps

By the end you can

  • Explain the 16.67 ms frame budget and why consistent frame times matter more than the average
  • Record and pause a MicroProfiler capture on the right side, and find a task in it
  • Use the Script Profiler, the Memory tool and Luau heap snapshots for the question each one answers, and time `--!native` before and after
  • Name what Beacon Yard sends or spawns every frame and every second, from its source

Before this: Debugging: breakpoints, the console, a method, The drone: movement, targeting, damage

Step 1 of 14

A hitch you can feel

Play Beacon Yard on a fast desktop and it feels smooth. Play it on an old phone during a drill and you might feel a stutter every few seconds. Nothing in Output is red. The game is correct and still feels wrong.

Performance work starts with one number. At 60 frames per second, each frame has 16.67 milliseconds to do everything: scripts, physics, animation, networking and rendering1. Go over and the frame arrives late. Players feel the late frames far more than they notice the average. Predict the maximum FPS if a task takes 100 ms every frame before running the cell.

Luau
Ctrl Enter runs the cell. Checked against the expected output
Work it out

A console game targets 30 FPS. How many milliseconds does each frame have? Round to two decimals.

ms

Link to this step · This confused me

Step 2 of 14

Three tools, three questions

Pick the tool by the question you are asking:

  • MicroProfiler asks: which task made this frame long? It draws one bar per frame and a timeline of the tasks inside each one. Open it with Ctrl+F6 (macOS: Cmd+F6) in Studio or the desktop client, and pause with Ctrl+P (macOS: Cmd+P) when you see a spike1.
  • Script Profiler asks: which Luau functions used the CPU over a recording? It only records functions that consume CPU, so a thread that waits (task.wait, a DataStore call) costs nothing in it2.
  • Memory and Luau heap in the Developer Console ask: what is growing? Memory shows megabytes by category over time; a heap snapshot lists the tables and functions your scripts hold3.
Match the pairs

Match each question to the tool that answers it.

Link to this step · This confused me

Step 3 of 14

Read a MicroProfiler capture

Roblox Studio
Roblox Studio with the MicroProfiler open over the viewport: a row of frame-time bars at the top and a timeline of labelled task blocks below.

Select a numbered pin, or a row below, to read what it marks.

The MicroProfiler paused during a drill. Bars along the top are frames; blocks below are the tasks inside them.

The workflow is always the same1:

  1. Play until the problem happens.
  2. Pause (Ctrl+P on Windows, Cmd+P on macOS) with the spike in view.
  3. Click the tall bar, then read the widest blocks in its timeline.
  4. Use Ctrl+F (macOS: Cmd+F) to jump to the slowest occurrence of a label.

Decide the side first. A spike in the HUD is a client capture. A spike in the drone or a coin handler is server work: in Studio solo Play both sides share your machine, and for a live server you record from the Developer Console's MicroProfiler tab, which saves a server dump.

Choose one

You suspect DroneService's Heartbeat step. Where should the capture come from?

You suspect DroneService's Heartbeat step. Where should the capture come from?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 4 of 14

What Beacon Yard does every frame

Read the source before you guess. One server connection runs every frame for the whole life of the server:

local function stepDrone(dt: number)
	local drone = current
	if not active or drone == nil or drone.model.Parent == nil then
		return
	end
 
	local stunned = isStunned(drone.root)
	paint(drone, stunned)
	if not stunned then
		moveDrone(drone, dt)
	end
	touchNearby(drone)

Outside a drill, stepDrone returns on its first line, so it costs almost nothing. During Active it moves one anchored model with PivotTo and checks who is near. PivotTo on a server part changes its CFrame, and that change replicates to every client, every frame, for as long as the drone exists.

The HUD, by contrast, refreshes its clock about ten times a second, not every frame:

		while screen.Parent ~= nil do
			renderClock()
			task.wait(0.1)

Text can wait a tenth of a second; nobody notices. A moving drone cannot, because its next position depends on the frame time dt.

Choose all that apply

Which of these run every frame during an Active drill?

Which of these run every frame during an Active drill?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 5 of 14

What Beacon Yard spawns every second

Particles are the other steady cost. MapBuilder gives the crystal a Motes emitter at rate 10 and each of the six pads one at rate 4. ExhibitService adds a lamp emitter at rate 8.

	motes(crystalAnchor, BEACON_COLOR, 10)
	for _, pad in pads do
		glow(pad, PAD_COLOR, 12, 2.2, false)
		motes(pad, PAD_COLOR, 4)

The server creates the emitters once and they replicate as objects. Each client then simulates and draws its own particles, so the cost lands on every player's device, during Idle as well as Active.

Work it out

Crystal at 10, six pads at 4 each, and the lamp at 8. How many particles per second does the yard emit?

particles per second

Link to this step · This confused me

Step 6 of 14

Memory: what keeps growing

Open the Developer Console (F9 or /console) and switch from Log to Memory to view live megabytes by category. The categories that are yours are PlaceMemory (instances, terrain, assets you loaded) and PlaceScriptMemory (your scripts)3. CoreMemory and CoreScriptMemory belong to the engine.

A leak is memory that grows and never comes back: a table that collects players and never removes them, a connection that is never disconnected, a sound that is never destroyed. Beacon Yard destroys every short sound twice over: when it ends, and again after 12 seconds if it somehow still exists.

	sound.Ended:Once(function()
		sound:Destroy()
	end)
	sound:Play()
	task.delay(12, function()
		if sound.Parent ~= nil then
			sound:Destroy()
		end

The method: take a Luau heap snapshot, play ten rounds, take another, and compare. Flat frame bars can hide a heap that only grows, until the phone runs out.

Choose one

Which pattern in the Memory tool suggests a leak?

Which pattern in the Memory tool suggests a leak?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 7 of 14

Tag memory by system with debug.setmemorycategory

When a Luau heap snapshot shows growth, the Memory Categories view groups every allocation by the category that was active when that object was created3. By default, each script gets a category named after the script itself, which lumps shared helper modules and callbacks together. Calling debug.setmemorycategory("DroneService") tags every allocation made by the current thread from that point on under "DroneService" (and debug.resetmemorycategory() clears the tag, while debug.getmemorycategory() reads the active one).

Tagging a service turns a wall of anonymous tables into one named row per system. Try it on DroneService in m14-ship, then revert the line afterwards. In Module 13, Lifetimes: signals, Trove and leak hunting tags every Beacon Yard service and runs a 200-player join/leave leak test against those categories.

Build along

m14-ship

  • src/server/DroneService.luau
  1. Near the top of src/server/DroneService.luau (and at the start of stepDrone or the drone spawn function), add debug.setmemorycategory("DroneService") and save.

    You should see DroneService.luau sets its memory category before creating the drone model and state table.

  2. Press Play, start a drill at the beacon, press F9, open LuauHeap, switch to Server, click Create Snapshot, and open the Memory Categories view. Find DroneService in the table.

    You should see The LuauHeap Memory Categories view lists a DroneService row with its allocated size and object count.

  3. Stop Play and revert src/server/DroneService.luau with git checkout -- src/server/DroneService.luau so your working tree stays clean.

    You should see git diff src/server/DroneService.luau is empty.

Choose one

You call debug.setmemorycategory("DroneService") after a table was already allocated at server boot. Which category owns that earlier table in LuauHeap's Memory Categories view?

You call debug.setmemorycategory("DroneService") after a table was already allocated at server boot. Which category owns that earlier table in LuauHeap's Memory Categories view?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 8 of 14

Network: what you replicate

Every property the server changes on a replicated instance is sent to every client that has it. The drone's per-frame PivotTo is the yard's biggest stream. Note which tool measures which kind of traffic: the Developer Console's Network tab only tracks HTTP/web calls (HttpService and DataStoreService), not instance replication. To measure replication traffic, use Network Stats (Shift+F3 in the client, or Ctrl+Shift+F3 / Cmd+Shift+F3 in Studio) and look for the ProcessPackets and Allocate Bandwidth and Run Senders scopes in the MicroProfiler4.

The server is broadcasting the match. Every property change is a frame of the broadcast, and every viewer receives it. A drone moving sixty times a second is sixty frames a second of footage sent to everyone.

Think of it as The live broadcast

Both sidesRemember: Replication is the live broadcast.

Cheaper options exist and each has a cost. Clients can animate the drone themselves from a target position the server sends a few times a second, or the server can stream positions over an UnreliableRemoteEvent. Both trade exactness for bandwidth, and both need the server to keep the real position for damage checks. Module 13's The network budget: measure, batch, pack measures Beacon Yard's real KB/s budget under load and replaces per-frame replication with packed snapshots.

Choose one

A second drone is added to the yard. What happens to the amount of drone position data that can be replicated during Active?

A second drone is added to the yard. What happens to the amount of drone position data that can be replicated during Active?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 9 of 14

Where the broadcast picture breaks

Where does it break?“The live broadcast” is a good picture of replication. Where does it stop being true?

It breaks here. Only property changes in some containers are sent, and nothing a client changes ever travels back up to the server.

The true model. The server copies changes in replicated containers, such as Workspace and ReplicatedStorage, down to clients. A client's own changes stay on that client unless it asks the server through a remote.

The broadcast picture suggests the server sends everything players see. Particles show where that breaks: the server sends the emitter once, and each client invents its own particles. That is why particles never show up as network traffic but do show up in a phone's frame time.

Choose one

The yard's 42 particles per second are expensive on a phone. Where does that cost appear?

The yard's 42 particles per second are expensive on a phone. Where does that cost appear?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 10 of 14

Measure, change one thing, measure again

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
MicroProfilerPer-frame timeline of engine tasks, in Studio, the desktop client, mobile (web UI) and server dumps.Any hitch or low frame rate.Dense; you need to know which labels are yours.
Script ProfilerCPU time by Luau function over a recording.Your scripts are the suspect.Waiting threads look free, so it hides slow yields.
Developer Console Memory and Luau heapMemory by category and snapshots of what scripts hold.Crashes on low-memory devices or slow growth over a session.Snapshots are big; compare two, do not stare at one.
Creator Hub Performance dashboardFrame rate, memory and crash data from real players' devices.After release, to find which devices suffer.Aggregated and delayed; it tells you where, not why.

Build along

m06-drone-wrench

  • src/server/DroneService.luau
  • src/server/MapBuilder.luau
  1. Press Play, start a drill at the beacon, and press Ctrl+F6 (macOS: Cmd+F6).

    You should see The MicroProfiler bar graph appears over the viewport and keeps scrolling.

  2. Press Ctrl+P (macOS: Cmd+P) while the drone is chasing you, click a bar and hover the blocks.

    You should see The graph freezes. Clicking a bar shows that frame's tasks; Heartbeat contains a small slice for the drone step during Active.

  3. Press F9, choose Memory, and expand PlaceScriptMemory.

    You should see Memory lists PlaceMemory and PlaceScriptMemory with sizes in MB. Note both numbers with the round phase.

  4. Write the baseline down before you change any emitter rate or the drone step.

    You should see Your notes say which side you captured, during which phase, and the two memory numbers. No game code was changed.

Link to this step · This confused me

Step 11 of 14

Profile a drill on the finished game

The MicroProfiler told you which frame was slow. Now ask the Script Profiler which of your functions used the CPU. Use the finished game at m14-ship, where the server runs two enemies: the drone and the scrap crawler.

They are scheduled differently. The drone steps on every Heartbeat. The crawler runs its own loop and sleeps between thinks:

		while crawler.alive and model.Parent ~= nil do
			tick(crawler)
			task.wait(Config.CRAWLER_TICK_SECONDS)

CRAWLER_TICK_SECONDS is 0.1, so the crawler thinks about ten times a second, while the drone steps sixty times a second. The Script Profiler lives in the Developer Console. It samples 1,000 times a second by default, and its Callgraph view groups functions by the frame task that ran them2.

Build along

m14-ship

  • src/server/DroneService.luau
  • src/server/CrawlerService.luau
  1. Check out m14-ship, press Play, and press F9. Open the tools dropdown, choose ScriptProfiler, and switch the client-server dropdown to Server.

    You should see The Developer Console shows the ScriptProfiler tool with Server selected and a Start button.

  2. Click Start, walk to the beacon and start a drill, survive it, then click Stop.

    You should see The recording runs while the drone chases you and the crawler hunts, then stops and shows a table sorted by time.

  3. In Callgraph, expand the Heartbeat node. Then type tick in the search box.

    You should see Under Heartbeat you find the drone's step function from DroneService. The crawler's tick is not under Heartbeat; searching for tick finds it.

  4. Switch to Functions, keep the unit in ms, and write down the top Beacon Yard function and its time. Then click Export to keep the session as JSON next to your notes.

    You should see Your notes name the Beacon Yard function at the top of the Functions view, its time in ms, and how long the recording ran. No code was changed.

Choose one

You expand Heartbeat in the Callgraph and find the drone's step, but no crawler code. Why?

You expand Heartbeat in the Callgraph and find the drone's step, but no crawler code. Why?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 12 of 14

--!native: measure before and after

Luau can compile a script to machine code for the CPU instead of interpreting it. You ask for it with one comment, --!native, on the first line, or with @native above a single function. It only runs natively in server scripts and in client scripts on Android, and it helps code that does a lot of arithmetic in Luau itself, especially functions called many times5. It is not free: compiling adds server start time and memory, and a game has a limit on how much native code it may hold.

The docs' advice is to time the code with and without it. That is this lesson's habit again: measure, change one thing, measure.

Build along

m14-ship

  1. In Studio, add a Script named NativeBench to ServerScriptService (in Studio only, not in your src folder), paste this, delete the first line, and press Play.

    luau
    --!native
    -- A throwaway timing script: layered waves over a grid, the math a terrain
    -- generator does. Delete it after you have your two numbers.
    local function height(x: number, z: number): number
    	local total, amplitude, frequency = 0, 1, 0.05
    	for _ = 1, 4 do
    		total += math.sin(x * frequency) * math.cos(z * frequency) * amplitude
    		amplitude *= 0.5
    		frequency *= 2
    	end
    	return total
    end
     
    local function field(size: number): number
    	local sum = 0
    	for x = 1, size do
    		for z = 1, size do
    			sum += height(x, z)
    		end
    	end
    	return sum
    end
     
    task.wait(8) -- time to start the Script Profiler first
    local start = os.clock()
    for _ = 1, 10 do
    	field(256)
    end
    print(string.format("NativeBench: %.0f ms", (os.clock() - start) * 1000))
    

    You should see Output prints one line such as NativeBench: followed by a time in ms. Write the number down.

  2. Stop, put --!native back as the first line, and press Play again.

    You should see A second time prints. Compare it with the first; on most machines the native run is faster, and you note by how much.

  3. Press Play once more. Within eight seconds, start a Server session in the Script Profiler, stop it after the NativeBench line prints, and find the two functions.

    You should see height and field appear with <native> next to their names. If they do not, a breakpoint in the script is the usual cause.

  4. Delete the NativeBench script.

    You should see NativeBench is gone from ServerScriptService, and git status in the game repo shows no change.

Choose one

Which Beacon Yard code is the best first candidate for --!native?

Which Beacon Yard code is the best first candidate for --!native?

Press 1 to 4 to choose, Enter to check.

Choose one

You added --!native to a module and the game feels the same. What do you check first?

You added --!native to a module and the game feels the same. What do you check first?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 13 of 14

Challenges

Level 1, Apprentice

Challenge

Pause one capture during a drill and label what you see.

Start from
The game at milestone m06 (download)

Done means

  • You pause a MicroProfiler capture during an Active drill
  • You say which side you recorded and point at Heartbeat in the timeline

Meet the criteria above, then record your own result. No test grades this check.

Choose one

DataService.saveUser waits 1 second between retries. How does that wait appear in the Script Profiler?

DataService.saveUser waits 1 second between retries. How does that wait appear in the Script Profiler?

Press 1 to 4 to choose, Enter to check.

Level 2, Builder

Challenge

Check whether the yard leaks across rounds.

Start from
The game at milestone m06 (download)

Done means

  • Two Luau heap snapshots, one after the first round and one after the fifth
  • A sentence on whether any category grew between them, with the numbers

Meet the criteria above, then record your own result. No test grades this check.

Level 3, Professional

Challenge

Fix the particle count in challenges/performance_work.luau. Grade the change on m14-ship: press Play and run this in the server command bar.

luau
game.ServerScriptService.RunGameTests:Invoke("performance")
Start from
The game at milestone m06 (download)
Grade it
To grade work from an earlier milestone, apply your challenge changes to a checkout based on m14-ship, which includes the Course Runner. In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("performance") in the server command bar. Copy the pass code from Output.

Done means

  • particlesPerSecond multiplies the pad rate by the pad count
  • Six pads give 42, one pad gives 22, a lamp alone gives 8
  • challenges/performance.luau prints TEST PASS yard_particles, one_pad and lamp_only

The Course Runner prints this code when the test passes.

Link to this step · This confused me

Step 14 of 14

Recap

Retiring the analogy

You no longer need “the live broadcast”. The server copies changes in replicated containers, such as Workspace and ReplicatedStorage, down to clients. A client's own changes stay on that client unless it asks the server through a remote.

Recap

  1. 60 FPS gives 16.67 ms per frame; consistent frame times matter more than the average.
  2. MicroProfiler for one frame, Script Profiler for CPU by function, Memory and heap snapshots for growth. Pick the side first.
  3. --!native compiles server scripts (and Android client scripts) to machine code. It helps heavy Luau arithmetic, costs start time and memory, and only counts once you have timed it both ways.
  4. Read the source for per-frame and per-second work, measure a baseline, change one thing, measure again.

Replication is the live broadcast, until only property changes in some containers are sent, and nothing a client changes ever travels back up to the server.

Next Parallel Luau: Actors and multithreading

Link to this step · This confused me