Profiling, Object Pools, and When to Optimize
▶ PRESS START
Lucas P. Cordova, Ph.D.
Willamette University | Tuesday, November 10, 2026
The Sprint 2 report and peer evaluation are due Thursday, November 12, 9:59 PM. The beta gate and content lock are Thursday, November 19.
The quest log
| When | What | Where |
|---|---|---|
| Thu Nov 12, 9:59 PM | Sprint 2 report and peer evaluation | docs/sprint-2.md; Review 2 sheets answered in FEEDBACK.md |
| Thu Nov 12, in class | Audio, the polish pipeline, and accessibility. Sprint 3 begins | Sprint 3 runs to the beta gate |
| Tue Nov 17 | Balancing and tuning with playtest evidence | Your numbers should live in data by then |
| Thu Nov 19, 9:59 PM | Beta gate, Stakeholder Review 3, content lock | All content in; draft itch.io page; tag beta |
| Thu Dec 3 | Showcase: guests play your game | The classroom arcade, Ford 202 |
Alpha closed the mechanics. From here the work is content, tuning, and a build that holds up on someone else's laptop. Today is the third one.
Sixteen milliseconds, sixty times a second
The frame budget is the time the game has to do everything for one picture: read input, run every _process and _physics_process, step physics, and draw. At 60 frames per second that is 1000 / 60 = 16.7 milliseconds. Miss it and the frame arrives late [3].
| Frames per second | Budget per frame | How it feels |
|---|---|---|
| 60 | 16.7 ms | Smooth. The target for every game in this room |
| 30 | 33.3 ms | Playable, a little heavy. Fast action starts to feel late |
| 20 | 50 ms | A slideshow. Players stop trusting the controls |
Week 2 gave you delta so the game moves at the same speed on every machine. Today is about what happens when delta itself gets too big.
| Low average | Spikes | |
|---|---|---|
| What the player sees | Everything is sluggish, all the time | Smooth, then a hitch, then smooth again |
| What the numbers say | Every frame is over budget | Most frames are fine. A few are huge |
| Usual cause | Work that grows with the number of things on screen | A lot of work landing in one frame: a spawn burst, a load |
| Where it shows | The FPS counter | The frame time graph. An FPS counter averages a hitch away |
Two different problems with two different cures. Today's demo has one of each.
Monitors, the Profiler, and a berry storm
MAIN.TSCN, AT DEMO8-LAP1Main (Node2D) game.gd ├─ Maze loaded by the brain ├─ Player ├─ Rival ├─ BerryStorm (Node2D) berry_storm.gd │ ├─ Berry (berry.tscn) an Area2D, hundreds of them │ └─ ... └─ UI (CanvasLayer) ├─ Banner, HUD, PauseMenu └─ PerfLabel (Label) perf_label.gd
The live demo starts on the tag demo8-lap1. Tags demo8-lap2 and branch demo8 are the catch-up points.
extends Label func _process(_delta: float) -> void: text = "FPS %d NODES %d" % [ Engine.get_frames_per_second(), Performance.get_monitor(Performance.OBJECT_NODE_COUNT)]
Engine.get_frames_per_second() is the same FPS the editor shows.Performance.get_monitor(...) reads any of the editor's monitors from code [4]. The node count is the one that catches a leak.Fingers up. The storm has about 800 berries alive and the game is far under 60 FPS. The biggest cost in each frame is:
1: creating 160 new berries every second.
2: drawing 800 sprites.
3: physics, checking 800 areas against Blitz.
4: something inside each berry's own script.
Hold your number. The profiler answers in a moment.
With demo8-lap1 open in Godot:
Monitors answer how bad, and is it getting worse. They record the whole run, so you can tick one after the bad moment and still see its history [3].
A node count that only climbs is a leak: things are spawned and never freed.
Still in the Debugger panel, game still running:
Inclusive time counts a function plus everything it calls. Self counts only its own body. Self is the one that names the culprit [3].
The row to find: _process in berry.gd, called about 800 times, holding nearly the whole frame.
func _process(delta: float) -> void: position += velocity * delta time_left -= delta # Berries should not pile up: push away from any berry that is too close. for other in get_tree().get_nodes_in_group("berries"): if other != self and position.distance_to(other.position) < 16.0: position += (position - other.position).normalized() * 20.0 * delta if time_left <= 0.0: queue_free()
get_nodes_in_group() builds a fresh 800-item array on each call, and it is called 800 times a frame.| Symptom | Cause, and the cure |
|---|---|
| The Profiler list is empty | Start was never clicked, or the game is not running. Run the project, then Start. |
| No Script Functions rows, or tiny times | The game is on the title screen, where the storm is off. Press Space in the game window, then profile. |
| Monitors show flat lines | Nothing is ticked. Tick FPS, Process, and Nodes in the list on the left. |
| The top row is a function that only calls other functions | Time is set to Inclusive. Switch it to Self. |
| The game got slower when profiling started | Expected: the profiler measures every call. Compare profiled runs with profiled runs. |
One change, then measure again
Stop the game. In the FileSystem dock, double-click berry.gd:
_process, select four lines: the comment that starts # Berries should not pile up, the for line, the if line, and the position += line under it._process is now five lines: move, count down, expire._process in berry.gd again.func _process(delta: float) -> void: position += velocity * delta time_left -= delta if time_left <= 0.0: queue_free()
Same 800 berries, same calls. The row that held the whole frame is now a rounding error.
Catch-up: git checkout demo8-lap2.
| Try, in this order | The question to ask | In a game |
|---|---|---|
| 1. Delete it | Does the player see or feel this work? | The pile-up loop. Off-screen enemies that still think |
| 2. Do it less often | Does it need to run every frame? | Enemy targeting on a 0.2 second Timer |
| 3. Do it once | Is the answer the same every time? | @onready a node; preload a scene; ask the group once in the manager |
| 4. Let the engine do it | Is there a node that does this already? | An Area2D instead of a distance loop; a TileMapLayer instead of 300 nodes |
| 5. Restructure | Is the cost in creating and destroying? | An object pool. Next section |
Each rung costs more of your time and adds more code than the one above it. Climb only as far as the budget needs.
| What the instruments show | Cause | Cure |
|---|---|---|
A _process at the top with a huge Calls count | A lookup or a loop inside every instance: get_node, find_child, a group query | Look it up once in _ready; move the loop to one manager |
| Nodes climbs and never comes down | Bullets, pickups, or effects that leave the screen and live forever | queue_free() on a lifetime, or on screen_exited from a VisibleOnScreenNotifier2D |
| Slow in the editor, with the Output panel scrolling | A print inside _process | Delete it, or print only when the value changes |
| Scripts are fast, Frame Time is still high | Drawing: huge textures, too many particles, many overlapping transparent sprites | The Visual Profiler tab; fewer, smaller things [3] |
| A spike on the first shot, the first explosion | A scene built and added to the tree mid-frame, many at once | preload, then a pool |
Reuse, and what it buys
func _spawn() -> void: var berry: Area2D = load("res://berry.tscn").instantiate() berry.position = Vector2( randf_range(area.position.x, area.end.x), randf_range(area.position.y, area.end.y)) berry.velocity = Vector2.from_angle(randf() * TAU) * drift_speed berry.time_left = berry_life berry.eaten.connect(_on_berry_eaten) add_child(berry)
demo8-lap2, run the project and press Space._spawn in berry_storm.gd._spawn in a single frame.An object pool builds a fixed set of objects once, up front. Using one means taking it out of the pool; finishing with one means putting it back. Nothing is created or destroyed while the game is running [5].
| You pay | You get |
|---|---|
| Every object exists from the first frame: more memory, more nodes, a longer start | No creation cost in the middle of play: the burst frame costs what a quiet frame costs |
| Reset code: a reused object must be scrubbed back to a fresh state | A hard cap: the pool size is the budget, so the count can never run away |
| An in-use flag, and a rule for what happens when the pool is empty | Predictable frames, which is what a hitch was missing |
func launch(at: Vector2, drift: Vector2, life: float) -> void: position = at velocity = drift time_left = life show() set_process(true) set_deferred("monitoring", true) func retire() -> void: if not visible: return # already resting in the pool hide() set_process(false) set_deferred("monitoring", false) retired.emit(self) func _process(delta: float) -> void: position += velocity * delta time_left -= delta if time_left <= 0.0: retire()
queue_free() is gone from this file. A finished berry retires and waits.launch() is the scrub: every field a previous flight touched gets a fresh value.visible doubles as the in-use flag, so a berry that is eaten and expires in the same frame retires once._process off, monitoring off._ready() calls retire(). A new berry's first act is to join the pool.const BERRY: PackedScene = preload("res://berry.tscn") var pool: Array[Area2D] = [] # berries that are resting, ready to launch func _ready() -> void: for i in pool_size: var berry: Area2D = BERRY.instantiate() berry.eaten.connect(_on_berry_eaten) berry.retired.connect(_on_berry_retired) add_child(berry) func _spawn() -> void: if pool.is_empty(): return # every berry is in the air: the pool is the budget var berry: Area2D = pool.pop_back() berry.launch( Vector2(randf_range(area.position.x, area.end.x), randf_range(area.position.y, area.end.y)), Vector2.from_angle(randf() * TAU) * drift_speed, berry_life) func _on_berry_retired(berry: Area2D) -> void: pool.append(berry)
preload once. _ready builds pool_size berries before the first frame.pop_back() and append() cost the same at any size.pool_size is the storm's whole budget, set in the Inspector.retired: signals up, again.| demo8-lap1 | demo8-lap2 | demo8 | |
|---|---|---|---|
| Scripts and physics per frame, 800 berries | 141 ms | 3.0 ms | 3.2 ms |
| The frame where a 400-berry burst lands | 228 ms | 63 ms | under 9 ms |
| Nodes in the tree | about 2,450 | about 2,450 | 3,640, always |
One test run on a Linux machine with rendering off. Your laptop prints different numbers with the same shape.
| Pool it | Leave it alone |
|---|---|
| Many identical, short-lived things: bullets, berries, sparks, damage numbers | One boss, six enemies, a dozen pickups placed in the level |
| They arrive in bursts, and the profiler shows the spike on the spawn function | They trickle in, and the frame graph is flat |
| A runaway count would hurt, so a hard cap is a feature | The count is small and fixed by the level design |
PackedVector2Array.Profile your alpha, on your laptop, in twenty minutes
| Your alpha | Profile this |
|---|---|
| Has a busy moment: many enemies, bullets, or effects at once | That moment. Start the profiler, play into it, stop |
| Hitches at one spot: the first shot, an explosion, a level load | Across the hitch. Click the spike on the graph and read the frame |
| Runs smooth everywhere | A stress test: multiply one spawn count by ten with an @export and find where it breaks |
| Is not running today | A fresh clone of rival-brains on demo8-lap1: find the loop and fix it yourself |
Teams work in the team repo. One laptop drives the game, the other drives the editor's Debugger panel and writes down numbers. Say your target out loud before the timer starts.
Twenty minutes, on the timer:
perf_label.gd from rival-brains.perf: the moment, the numbers, the top function.Stuck? The Nothing happened? slide, then The usual suspects, then a hand up.
perf issue with the numbers in it and spend the sprint on content.Measure, find the biggest cost, fix that one thing, measure again. Stop when the game is inside its budget.
Sprint 2 closes Thursday
The rest of class is yours. Both laptops on the team repo. Sprint 2 closes Thursday night with the report and the peer evaluation.
| Ask yourselves | Because |
|---|---|
Does every Review 2 sheet have an adopt, adapt, or decline line in FEEDBACK.md? | The Sprint 2 report points at that log, and your stakeholders read it at beta |
| Is the board true? Closed cards closed, cut MUSTs marked cut? | The report quotes the board. Fix the board first and the report writes itself |
| What is on the Sprint 3 list that is content, and what is still a mechanic? | Beta is content lock. A mechanic on that list is a scope conversation to have today |
Did the build-along open a perf issue? | It goes on the Sprint 3 board with an owner |
I am walking the room. Flag me down for anything stuck.
What you know now
Thu Nov 12: Sprint 2 report and peer evaluation, 9:59 PM; audio, polish, and accessibility in class. Thu Nov 19: the beta gate, Stakeholder Review 3, and content lock.
get_monitor, monitor list, debug-only monitors).github.com/LucasCordova/rival-brains, branch demo8, tags demo8-lap1 and demo8-lap2.