CS 276 // GAME SYSTEMS IN GODOT

Sixteen Milliseconds.

Profiling, Object Pools, and When to Optimize

Lucas P. Cordova, Ph.D.

Willamette University  |  Tuesday, November 10, 2026

SCORE 000276HI 999999

Outline

QUEST LOG

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.

CS 276
LEVEL 01

Save Point

The quest log

SCORE 000276HI 999999

Quest log

WhenWhatWhere
Thu Nov 12, 9:59 PMSprint 2 report and peer evaluationdocs/sprint-2.md; Review 2 sheets answered in FEEDBACK.md
Thu Nov 12, in classAudio, the polish pipeline, and accessibility. Sprint 3 beginsSprint 3 runs to the beta gate
Tue Nov 17Balancing and tuning with playtest evidenceYour numbers should live in data by then
Thu Nov 19, 9:59 PMBeta gate, Stakeholder Review 3, content lockAll content in; draft itch.io page; tag beta
Thu Dec 3Showcase: guests play your gameThe classroom arcade, Ford 202
CHECKPOINT

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.

CS 276
LEVEL 02

The Frame Budget

Sixteen milliseconds, sixty times a second

SCORE 000276HI 999999

A frame is a deadline

DEFINITION

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 secondBudget per frameHow it feels
6016.7 msSmooth. The target for every game in this room
3033.3 msPlayable, a little heavy. Fast action starts to feel late
2050 msA 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.

CS 276

Two ways to be slow

Low averageSpikes
What the player seesEverything is sluggish, all the timeSmooth, then a hitch, then smooth again
What the numbers sayEvery frame is over budgetMost frames are fine. A few are huge
Usual causeWork that grows with the number of things on screenA lot of work landing in one frame: a spawn burst, a load
Where it showsThe FPS counterThe frame time graph. An FPS counter averages a hitch away
CHECKPOINT

Two different problems with two different cures. Today's demo has one of each.

CS 276

Measure, then fix the biggest thing

  • Knuth, 1974: programmers burn enormous time worrying about the speed of code that does not matter, and that worry makes the code harder to debug. About 3 percent of a program deserves the attention [2].
  • Reading the code will not tell you which 3 percent. Intuition about where the time goes is unreliable.
  • The engine can tell you. Godot ships the instruments in the Debugger panel [3].
THE LOOP
  1. Measure. Put a number on the problem.
  2. Find the biggest cost. One function, by name.
  3. Fix that one thing.
  4. Measure again. Stop when the game is inside its budget [1].
CS 276
LEVEL 03

Measure First

Monitors, the Profiler, and a berry storm

SCORE 000276HI 999999

A teammate merged the storm

MAIN.TSCN, AT DEMO8-LAP1
Main (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
  • BerryStorm rains marionberries on the maze: 160 a second, each one drifting for five seconds. About 800 are alive at any moment.
  • Blitz eats them for the BERRIES count on the HUD. Eating the fig (or pressing B in the game) drops a burst of 400 more.
  • The pull request looked fine. The game now runs like a slideshow.
LIVE DEMO

The live demo starts on the tag demo8-lap1. Tags demo8-lap2 and branch demo8 are the catch-up points.

CS 276

perf_label.gd: a number on the screen

extends Label

func _process(_delta: float) -> void:
    text = "FPS %d   NODES %d" % [
            Engine.get_frames_per_second(),
            Performance.get_monitor(Performance.OBJECT_NODE_COUNT)]
  • One Label on the UI layer, one script. Copy it into your game today.
  • 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.
  • It keeps working in the exported build, where there is no editor to ask. (A few monitors only report in debug builds [4].)
CS 276

Predict: where is the time going?

PREDICT

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.

CS 276

Lap 1, step 1: Monitors

LIVE DEMO

With demo8-lap1 open in Godot:

  1. Run the project. In the game window, press Space to start. Read the label in the bottom-left corner.
  2. Leave the game running and click back on the editor. At the bottom of the editor, click Debugger.
  3. Inside the Debugger panel, click the Monitors tab.
  4. In the list on the left, under Time, tick FPS and Process. Under Object, tick Nodes. Each tick adds a graph.
  5. Read the three graphs: FPS far under 60, Process far over 16.7 ms, Nodes in the thousands and wobbling.
  6. Back in the game, press B. Watch all three graphs react to the burst.
PATTERN

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.

CS 276

Lap 1, step 2: the Profiler

LIVE DEMO

Still in the Debugger panel, game still running:

  1. Click the Profiler tab. It is empty: the profiler is off until asked, because measuring costs time too.
  2. Click Start in the top-left corner of the tab. Play for five seconds. Click Stop.
  3. Click anywhere on the graph on the right. The list on the left now shows that one frame.
  4. Set the Time drop-down to Self, and leave Measure on Frame Time (ms).
  5. Scroll the list down past Physics and Audio to Script Functions.
  6. Find the row with the largest time. Read its name, its time, and its Calls.
DEFINITION

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.

CS 276

berry.gd: the hot function

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()
  • Every berry asks the tree for every berry, every frame. 800 berries times 800 others is 640,000 distance checks per frame.
  • get_nodes_in_group() builds a fresh 800-item array on each call, and it is called 800 times a frame.
  • Double the berries and the cost goes up four times. That is why the burst hurts so much.
  • Now the design question: what does the player get for those 640,000 checks?
CS 276

Nothing happened?

SymptomCause, and the cure
The Profiler list is emptyStart was never clicked, or the game is not running. Run the project, then Start.
No Script Functions rows, or tiny timesThe game is on the title screen, where the storm is off. Press Space in the game window, then profile.
Monitors show flat linesNothing is ticked. Tick FPS, Process, and Nodes in the list on the left.
The top row is a function that only calls other functionsTime is set to Inclusive. Switch it to Self.
The game got slower when profiling startedExpected: the profiler measures every call. Compare profiled runs with profiled runs.
CS 276
LEVEL 04

Fix the Biggest Thing

One change, then measure again

SCORE 000276HI 999999

Lap 2: delete the loop

LIVE DEMO

Stop the game. In the FileSystem dock, double-click berry.gd:

  1. In _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.
  2. Delete them. _process is now five lines: move, count down, expire.
  3. Save the script.
  4. Run the project and press Space. Read the label in the corner.
  5. In the editor: Debugger, Monitors. Read FPS and Process again.
  6. Profiler, Start, five seconds, Stop. Find _process in berry.gd again.
func _process(delta: float) -> void:
    position += velocity * delta
    time_left -= delta
    if time_left <= 0.0:
        queue_free()
CHECKPOINT

Same 800 berries, same calls. The row that held the whole frame is now a rounding error.

Catch-up: git checkout demo8-lap2.

CS 276

The ladder of fixes

Try, in this orderThe question to askIn a game
1. Delete itDoes the player see or feel this work?The pile-up loop. Off-screen enemies that still think
2. Do it less oftenDoes it need to run every frame?Enemy targeting on a 0.2 second Timer
3. Do it onceIs the answer the same every time?@onready a node; preload a scene; ask the group once in the manager
4. Let the engine do itIs there a node that does this already?An Area2D instead of a distance loop; a TileMapLayer instead of 300 nodes
5. RestructureIs 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.

CS 276

The usual suspects

What the instruments showCauseCure
A _process at the top with a huge Calls countA lookup or a loop inside every instance: get_node, find_child, a group queryLook it up once in _ready; move the loop to one manager
Nodes climbs and never comes downBullets, pickups, or effects that leave the screen and live foreverqueue_free() on a lifetime, or on screen_exited from a VisibleOnScreenNotifier2D
Slow in the editor, with the Output panel scrollingA print inside _processDelete it, or print only when the value changes
Scripts are fast, Frame Time is still highDrawing: huge textures, too many particles, many overlapping transparent spritesThe Visual Profiler tab; fewer, smaller things [3]
A spike on the first shot, the first explosionA scene built and added to the tree mid-frame, many at oncepreload, then a pool
CS 276
LEVEL 05

The Object Pool

Reuse, and what it buys

SCORE 000276HI 999999

The hitch that is left

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)
LIVE DEMO
  1. On demo8-lap2, run the project and press Space.
  2. Profiler, Start. In the game, press B three times, a second apart. Stop.
  3. Click a spike on the graph. Find _spawn in berry_storm.gd.
  • The average is fine now. The burst is 400 calls to _spawn in a single frame.
  • Each call builds three nodes from the scene file, registers an Area2D with the physics server, wires a signal, and enters the tree.
  • Five seconds later the same 400 berries are freed. Then the next burst builds them all again.
CS 276

Object pool

DEFINITION

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 payYou get
Every object exists from the first frame: more memory, more nodes, a longer startNo 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 stateA 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 emptyPredictable frames, which is what a hitch was missing
CS 276

berry.gd, pooled

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.
  • A resting berry costs almost nothing: hidden, _process off, monitoring off.
  • _ready() calls retire(). A new berry's first act is to join the pool.
CS 276

berry_storm.gd, pooled

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.
  • The pool is an Array. pop_back() and append() cost the same at any size.
  • Empty pool: no spawn. The export pool_size is the storm's whole budget, set in the Inspector.
  • The storm never asks a berry whether it is busy. Berries report in through retired: signals up, again.
CS 276

The scoreboard

demo8-lap1demo8-lap2demo8
Scripts and physics per frame, 800 berries141 ms3.0 ms3.2 ms
The frame where a 400-berry burst lands228 ms63 msunder 9 ms
Nodes in the treeabout 2,450about 2,4503,640, always

One test run on a Linux machine with rendering off. Your laptop prints different numbers with the same shape.

  • Deleting four lines bought a 47 times faster frame. The pool changed the average by nothing you could measure.
  • The pool's whole job was the second row: the hitch went from four dropped frames to none.
  • The third row is the price: 3,640 nodes from the first frame, title screen included.
CS 276

When a pool earns its place

Pool itLeave it alone
Many identical, short-lived things: bullets, berries, sparks, damage numbersOne boss, six enemies, a dozen pickups placed in the level
They arrive in bursts, and the profiler shows the spike on the spawn functionThey trickle in, and the frame graph is flat
A runaway count would hurt, so a hard cap is a featureThe count is small and fixed by the level design
  • In engines with a garbage collector, pools are everywhere because freeing memory causes pauses. GDScript frees an object the moment you ask, so in Godot a pool is only about the cost of building nodes in a burst [6].
  • Data locality, the other reading [7]: a processor is fastest on plain data packed side by side. In Godot you get that by handing the engine one big job: a TileMapLayer, a GPUParticles2D, a MultiMeshInstance2D, a PackedVector2Array.
CS 276
LEVEL 06

Build-Along

Profile your alpha, on your laptop, in twenty minutes

SCORE 000276HI 999999

Pick your target

Your alphaProfile this
Has a busy moment: many enemies, bullets, or effects at onceThat moment. Start the profiler, play into it, stop
Hitches at one spot: the first shot, an explosion, a level loadAcross the hitch. Click the spike on the graph and read the frame
Runs smooth everywhereA stress test: multiply one spawn count by ten with an @export and find where it breaks
Is not running todayA fresh clone of rival-brains on demo8-lap1: find the loop and fix it yourself
CO-OP MODE

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.

CS 276

Co-op: find your frame

CO-OP MODE

Twenty minutes, on the timer:

  1. Add the perf label: a Label on your UI layer with perf_label.gd from rival-brains.
  2. Run. Debugger, Monitors: tick FPS, Process, and Nodes. Write the three numbers down.
  3. Profiler, Start, play your target moment, Stop. Time on Self. Write down the top three script functions.
  4. Open an issue labeled perf: the moment, the numbers, the top function.
  5. If the top function has a fix on the first three rungs of the ladder, make it and measure again.
  6. Round clear: show me a number from before, and either a number from after or the issue.

Stuck? The Nothing happened? slide, then The usual suspects, then a hand up.

CS 276

Round clear

  • Every team has a number now. A complaint that the game feels slow has become a function name and a time.
  • Inside the budget with headroom? Close the perf issue with the numbers in it and spend the sprint on content.
  • Over the budget? The issue goes on the Sprint 3 board, with the top function in its title.
  • Keep the perf label in the build through beta. Your stakeholders play on their own laptops at the beta gate.
CHECKPOINT

Measure, find the biggest cost, fix that one thing, measure again. Stop when the game is inside its budget.

CS 276
LEVEL 07

Studio

Sprint 2 closes Thursday

SCORE 000276HI 999999

Sprint 2 studio

CO-OP MODE

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

CS 276
LEVEL 08

Game Over Screen

What you know now

SCORE 000276HI 999999

Checkpoint reached

CHECKPOINT
  • A frame at 60 FPS has 16.7 ms. Slow comes in two kinds: a low average and spikes.
  • Monitors say how bad and whether it is growing. The Profiler, on Self time, names the function.
  • Fix the biggest cost first, with the cheapest rung of the ladder: delete, do less often, do once, let the engine do it.
  • An object pool trades memory and reset code for flat frames during a burst. Measure before and after.
  • A node count that only climbs is a leak. A perf label in the corner catches it on any machine.
  • There is a stopping rule: inside the budget on the slowest laptop that has to run the game is done.
QUEST LOG

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.

CS 276

Sources

  • [1] Godot docs: General optimization tips (measuring, bottlenecks, the profile and optimize loop).
  • [2] Knuth, Structured Programming with go to Statements, ACM Computing Surveys 6(4), 1974.
  • [3] Godot docs: The Profiler; Debugger panel (Monitors, Profiler, Visual Profiler).
  • [4] Godot docs: Performance class reference (get_monitor, monitor list, debug-only monitors).
  • [5] Nystrom, Game Programming Patterns: Object Pool. gameprogrammingpatterns.com/object-pool.html
  • [6] Godot docs: CPU optimization (languages, the SceneTree, physics).
  • [7] Nystrom, Game Programming Patterns: Data Locality. gameprogrammingpatterns.com/data-locality.html
  • [8] Demo repo: github.com/LucasCordova/rival-brains, branch demo8, tags demo8-lap1 and demo8-lap2.
CS 276