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

1A 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
local fps = 60
local budget = 1000 / fps
print(string.format("%.2f ms per frame", budget))
-- A task that takes 100 ms every frame:
print(string.format("%.0f FPS at best", 1000 / 100))
Figure 1.1. Expected output: 16.67 ms per frame 10 FPS at best

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

Answer

33.33 ms (within 0.01). 1000 / 30 = 33.33 ms. Halving the frame rate doubles the budget, which is why 30 FPS targets exist for heavy scenes.

Open this step in lesson mode · Link to this step · This confused me

2Three 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 each question to the tool that answers it.

  1. Why did this one frame take 40 ms?
  2. Which function used the most CPU during a drill?
  3. Is script memory still climbing after ten rounds?
  4. Which tables are keeping old sounds alive?
Answer

Why did this one frame take 40 ms?: MicroProfiler; Which function used the most CPU during a drill?: Script Profiler; Is script memory still climbing after ten rounds?: Developer Console Memory; Which tables are keeping old sounds alive?: Luau heap snapshot. The MicroProfiler is per frame, the Script Profiler sums CPU by function, Memory tracks categories over time, and a heap snapshot shows what is referenced.

Open this step in lesson mode · Link to this step · This confused me

3Read 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.

Figure 3.1.

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.

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

  1. The server, because DroneService runs in src/server
  2. The client, because the drone is visible there
  3. Either; they show the same tasks
  4. Neither; the MicroProfiler cannot see scripts
Answer

The server, because DroneService runs in src/server. The server steps the drone. The client only receives its new CFrame and draws it. A client capture shows rendering, not the server's step.

Open this step in lesson mode · Link to this step · This confused me

4What 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)
Figure 4.1

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)
Figure 4.2

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

Which of these run every frame during an Active drill?

  1. DroneService's Heartbeat step
  2. Replicating the drone's new CFrame to clients
  3. The HUD clock text update
  4. Saving the player's profile
Answer

DroneService's Heartbeat step; Replicating the drone's new CFrame to clients. The drone step and its replication are per frame. The HUD updates about ten times a second, and DataService saves on leave and at shutdown, never on Heartbeat.

Open this step in lesson mode · Link to this step · This confused me

5What 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)
Figure 5.1

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.

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

Answer

42 particles per second. 10 + 6 × 4 + 8 = 42. Forgetting the multiplier gives 22, which is the bug in this lesson's Level 3 challenge.

Open this step in lesson mode · Link to this step · This confused me

6Memory: 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
Figure 6.1

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.

Which pattern in the Memory tool suggests a leak?

  1. PlaceScriptMemory rises a little after every round and never drops back
  2. Memory jumps when the drill starts and falls when it ends
  3. CoreMemory changes when a player joins
  4. PlaceMemory is larger than PlaceScriptMemory
Answer

PlaceScriptMemory rises a little after every round and never drops back. Rising and falling with the round is normal work. A staircase that only goes up means something is kept forever; take two heap snapshots to find it.

Open this step in lesson mode · Link to this step · This confused me

7Tag 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.

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?

  1. Whatever category was active when the table was allocated, because the engine assigns categories at allocation time
  2. DroneService, because setmemorycategory renames every existing table in the script
  3. CoreMemory, because tables created at boot belong to the engine
  4. Neither; tables only appear in the Graph view
Answer

Whatever category was active when the table was allocated, because the engine assigns categories at allocation time. Categories are stamped at allocation time. Put debug.setmemorycategory at the top of a service or entry point before it builds tables and closures, so every allocation lands under that system's name.

Open this step in lesson mode · Link to this step · This confused me

8Network: 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.

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

  1. It can roughly double because there are two moving drones instead of one
  2. Nothing; replication is free
  3. It halves, because the drones share a frame
  4. It only affects the server's CPU
Answer

It can roughly double because there are two moving drones instead of one. Each moving model is its own stream. Profile the second drone before adding a third.

Open this step in lesson mode · Link to this step · This confused me

9Where 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.

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

  1. On each client's CPU and GPU, because each client simulates and draws its own particles
  2. On the server's network, one packet per particle
  3. Only in the server's MicroProfiler
  4. In the DataStore budget
Answer

On each client's CPU and GPU, because each client simulates and draws its own particles. Particles are simulated and rendered on each client. Reduce the rate, the lifetime or the number of emitters to save phone frame time.

Open this step in lesson mode · Link to this step · This confused me

10Measure, 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.

Open this step in lesson mode · Link to this step · This confused me

11Profile 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)
Figure 11.1

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.

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

  1. The crawler loop wakes from task.wait every 0.1 seconds instead of connecting to Heartbeat, so its time sits under another task
  2. The crawler runs on the client, so a server recording cannot see it
  3. The Script Profiler only records functions that run every frame
  4. The crawler uses PathfindingService, so it costs no CPU
Answer

The crawler loop wakes from task.wait every 0.1 seconds instead of connecting to Heartbeat, so its time sits under another task. Callgraph groups functions by the frame task that ran them. The drone is connected to Heartbeat; the crawler wakes up from task.wait, so you find it by searching for tick, not by looking under Heartbeat.

Open this step in lesson mode · Link to this step · This confused me

12--!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.

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

  1. A pure numeric function the server calls many times, such as a noise or grid generator
  2. Hud.luau, the client script that updates the clock text
  3. The top level of a server module that runs once at start
  4. Every script, just in case
Answer

A pure numeric function the server calls many times, such as a noise or grid generator. Pick server code that does heavy arithmetic many times, measure it with and without the comment, and keep --!native only where the numbers say it helps.

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

  1. Whether the Script Profiler shows the module's functions as native, and your before and after timings
  2. Whether the module has a .native.luau extension
  3. Whether the place is published
  4. Whether the client has enabled native code in its settings
Answer

Whether the Script Profiler shows the module's functions as native, and your before and after timings. A breakpoint, discouraged code or wrongly typed arguments can keep a function interpreted. The profiler's native marker tells you, and the timings tell you if it was worth it.

Open this step in lesson mode · Link to this step · This confused me

13Challenges

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

Hints

  1. Ctrl+F6 (macOS: Cmd+F6) opens it, Ctrl+P (macOS: Cmd+P) pauses it.
  2. Use Ctrl+F (macOS: Cmd+F) and search for Heartbeat.

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

  1. It does not appear, because the profiler only records CPU time and the thread is sleeping
  2. As one second of CPU time
  3. As a red error
  4. As four seconds of CPU time
Answer

It does not appear, because the profiler only records CPU time and the thread is sleeping. Waiting threads are not recorded. A slow save shows up as delay, not as CPU, so the Script Profiler alone would miss it.

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

Hints

  1. Use the LuauHeap tool in the Developer Console on the client and on the server.
  2. Compare the same view in both snapshots.

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

Hints

  1. The signature already receives padCount.
  2. Do not hard-code 42.
Solution
luau
function Work.particlesPerSecond(crystalRate: number, padCount: number, padRate: number, lampRate: number): number
	return crystalRate + padCount * padRate + lampRate
end

Open this step in lesson mode · Link to this step · This confused me

14Recap

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

Open this step in lesson mode · Link to this step · This confused me