coloX Development Tips and Optimization
Tips for cartridge development: memory savings, frame rate optimization, and audio/image/network usage. See the topic documents for API details.
Contents
- Performance and memory monitoring
- Frame rate and CPU optimization
- Saving memory
- Audio tips
- Image tips
- Networking and JSON tips
- Cartridge size
- Development and debugging
1. Performance and Memory Monitoring
Measure before optimizing. Query these at any time inside a cartridge:
local cpu = stat(1) -- CPU usage in the previous frame (0~1)
local fps = stat(7) -- Current frame rate
local mem = stat(0) -- Memory usage in KB
Keep a global debug overlay during development (frame/FPS/CPU, a short 15-frame average, persistent across cartridges):
statctl('dfps', 1) -- Enable; remove before release
Adapt to the device speed level when physical-device performance is insufficient (see platforms.md):
local QUALITY = (__vm_speed_lvl >= 60) and 2 or 1 -- Higher quality on fast devices
2. Frame Rate and CPU Optimization
Local API bindings. Global lookups cost time; bind frequently called drawing functions to locals at the top of the file (significant effect; used in examples/shootingstar.clx):
local print, pset, line, cos, sin = print, pset, line, cos, sin
Partial redrawing. Do not redraw static backgrounds every frame. Use clip() to refresh only dynamic regions; clip/camera return their old values for restoring after a drawing block:
local ox, oy, ow, oh = clip(0, 100, 240, 40) -- Refresh only the bottom status bar
draw_statusbar()
clip(ox, oy, ow, oh)
Reduce per-frame allocation. {...} tables and string concatenation create garbage. Reuse tables outside the loop and rebuild strings only when their contents change.
Run heavy logic every other frame. Perform collision/AI computations on alternate frames while drawing every frame, preserving visual smoothness with half the CPU:
frame = (frame + 1) % 2
if frame == 0 then update_ai() end -- AI 30fps
Refresh during lengthy operations. Use flip() to present progress immediately during batch processing, avoiding an apparent freeze (see graphics.md).
3. Saving Memory
Generational GC. For long-lived cartridges with small incremental changes (watch faces/utilities), use generational collection to reduce GC pauses:
collectgarbage('generational')
Explicitly release large objects. After finishing with an image/animation, call img_close(), set it to nil, then trigger collection manually:
img_close(big)
big = nil
collectgarbage()
Two TTF precautions: Keep a reference to the object returned by font_add (a global is recommended), otherwise rendering by name fails after GC. Call font_close when finished. After rendering large fonts, use font_shrink() to release cached memory (see text.md).
Decode GIF/WebP on demand. Stream frames and honor their delays; do not stack all frames with gifall=true unless random frame access is actually needed:
local has, delay = img_gif_next(gif) -- Decode the next frame only when due
Release large strings promptly. Set large strings such as #blob data and HTTP bodies to nil when finished; do not retain them long-term in globals/closures.
4. Audio Tips
- Small speakers cannot reproduce low frequencies: pitch 0-7 (approximately 65-98Hz) is almost inaudible; use bass ≥12 and melody 24-48 (see audio pitfalls in audio.md).
- Generate sfx data with scripts rather than writing hex by hand (misalignment makes the whole effect silent without an error).
- Feed long audio as a stream:
wave()without arguments returns free space. Feed another chunk only when space is available, avoiding data loss from filling it at once (complete example in audio.md). - Embed compressed audio:
#blob :e:/:g:/:o:(ADPCM/G.711A/Opus) saves 50%-75% of cartridge size compared with raw PCM.
5. Image Tips
- JPEG suits infrequent pulls, not video: approximately 10-30ms per frame with hardware decoding, 150-500ms for 480x480 software decoding (incoming streams: img.md).
- Zero-copy screen/sprite subregions:
img_loadscr("SCR", ...)wraps existing memory without copying pixels. - Skip VG canvas clearing for speed:
img_set_flag(canvas, '+', 8)(skip clearing, provided you ensure complete screen coverage). - Use 16bpp instead of 32bpp: When sufficient, 16bpp (RGB565) halves image and canvas memory. 8bpp/4bpp save even more.
- Prefer smaller specifications: For pixel-art applications, smaller canvases enlarged by the system are most efficient. For example, a 240x240 application is automatically enlarged on a 480x480 platform.
6. Networking and JSON Tips
- Call
copas.step()every frame, or all network I/O stalls (see net.md). - Use
cjson_safefor external JSON: Network data is untrusted; decode failures returnnil, errrather than throwing and interrupting the cartridge (see cjson.md). - Use
string.packfor binary protocols: Faster and less error-prone than manual shifts and byte-string concatenation (see lua.md). - DNS resolution blocks: Cold-cache DNS may stall for several milliseconds; use IP addresses directly in timing-sensitive loops.
- Use lowercase string keys: Access HTTP response headers with
headers["content-length"].
7. Cartridge Size
- Embed large resources with
#blob :z:(zlib), decompressing withdecompress()at runtime. - Import sprite sheets directly with
#png; more compact and less error-prone than handwritten hex. - ROM limits vary significantly (approximately 74KB for coloX-4, 1.6MB for 32W); choose specifications carefully for resource-heavy cartridges (see platforms.md).
8. Development and Debugging
printh(...)outputs to the host console (printdraws on screen; do not confuse them).- Fast desktop iteration:
tools/coloXtest -d <directory>/ -r <cartridge>.clxruns a cartridge directly without a full build. - Automated tests/screenshots/button injection use the host debugging protocol (TCP 3563); CI golden-image checks can compare the response's pixel md5 directly (see debug.md).
- When fixing bugs, first enable
statctl('dfps', 1)to check CPU saturation; most unexplained stutters come from per-frame allocations or full-screen redraws.