Performance Optimization for Constrained Devices Questions
Optimizing software that runs on a resource-constrained device or platform, not a server or cloud fleet: mobile apps, embedded and IoT firmware, and game clients operating under hard limits on memory, CPU, battery, and bandwidth. Covers memory and CPU envelope budgeting, power and energy efficiency, platform-specific profiling and toolchains (ARM/MCU debugging, RTOS scheduling), firmware-level concurrency and interrupt handling (ISR design, DMA, priority inversion, lock-free versus locking trade-offs), fixed-point arithmetic and numeric-precision trade-offs on FPU-less hardware, binary and asset size reduction, and on-device model or asset compression. Explicitly excludes server-side, cluster, or cloud-fleet performance work (profiling a Kubernetes service, tuning JVM garbage collection on a backend, scaling a distributed cache) even when phrased as optimizing under constraints: that content belongs to this catalog's server-performance topics.
Implement in C a fixed-size memory pool allocator suitable for embedded systems. Requirements: initialize the pool in O(1), allocate and free fixed-size blocks in O(1), and be safe for single-core usage where free may be called from an ISR. Provide the core functions and explain concurrency handling choices.
Sample Answer
Approach
The spec asks for O(1) pool_init, not just O(1) pool_alloc/pool_free, and for pool_free to be safe when called from an ISR on a single core. The original design fails both, in ways that only show up under scrutiny, not on a casual read.
First, pool_init: threading a free list through every block at init time (visiting each of the n blocks once) is O(n) total, not O(1), even though each individual step is O(1), the same way n separate O(1) insertions into an array still add up to an O(n) fill, not an O(1) one. A genuinely O(1) init needs the pool to avoid touching any block until that specific block is actually requested. The standard trick: track how many blocks have ever been handed out with a monotonically increasing counter (num_never_touched), and derive a never-yet-used block's address lazily as pool_start + index * block_size instead of pre-threading it onto a list. pool_init then only sets a handful of scalar fields, no loop over the buffer, true O(1). Freed blocks go onto a small explicit free-list stack (the same intrusive-pointer trick as before, just scoped to blocks that have actually been freed at least once), so pool_alloc checks that stack first and only falls back to the lazy counter for blocks that have never been touched.
Second, concurrency: it's tempting to protect only pool_free, on the theory that "only pool_free is called from an ISR, so only it needs protection." That misses the actual hazard: pool_alloc runs on the main/foreground context, and its pop (whether from the free-list stack or the lazy counter) is a non-atomic read-then-write at the machine-code level, read the current state, then later write the updated state back. There's a real window between those two steps. If an ISR fires in that window and calls pool_free, pushing a block onto the free-list stack, main-context then resumes and overwrites the stack pointer with the stale value it captured before the push happened, silently discarding the block the ISR just freed. That block becomes permanently unreachable (a one-block leak) and free_count desyncs from reality, forever, since nothing later corrects it. What matters isn't which function runs in the ISR, it's whether main-context's multi-step access to shared state can be caught mid-flight by anything that mutates that same state, and here it can, so both pool_alloc and pool_free need the critical section, not just pool_free.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
typedef struct pool_block {
struct pool_block *next;
} pool_block_t;
typedef struct {
uint8_t *pool_start;
size_t block_size;
size_t block_count;
size_t num_never_touched; /* blocks [0, num_never_touched) have been handed out at least once */
pool_block_t *free_list; /* stack of blocks that WERE handed out and have since been freed */
size_t free_count;
} mem_pool_t;
/* On real hardware these map to __disable_irq()/__enable_irq() (Cortex-M) or
* a saved PRIMASK/BASEPRI; stubbed here so the demo runs on a host. */
static uint32_t enter_critical(void) { return 0; }
static void exit_critical(uint32_t saved_state) { (void)saved_state; }
/* O(1): store scalars only, no loop over the buffer. Never-touched blocks are
* addressed lazily (pool_start + index * block_size) instead of being
* pre-threaded onto a free list at init time. */
void pool_init(mem_pool_t *pool, uint8_t *buffer, size_t block_size, size_t block_count) {
pool->pool_start = buffer;
pool->block_size = block_size;
pool->block_count = block_count;
pool->num_never_touched = 0;
pool->free_list = NULL;
pool->free_count = block_count;
}
/* O(1): pop the explicit free-list stack first (blocks handed out before and
* since freed); only touch a never-used block, at its lazily-computed
* address, once that stack is empty. The WHOLE body, both branches, runs
* inside the critical section: an ISR calling pool_free() cannot interleave
* with either branch's read-then-write, closing the leak/desync window
* described above. */
void *pool_alloc(mem_pool_t *pool) {
uint32_t state = enter_critical();
if (pool->free_list != NULL) {
pool_block_t *blk = pool->free_list;
pool->free_list = blk->next;
pool->free_count--;
exit_critical(state);
return (void *)blk;
}
if (pool->num_never_touched < pool->block_count) {
void *blk = pool->pool_start + pool->num_never_touched * pool->block_size;
pool->num_never_touched++;
pool->free_count--;
exit_critical(state);
return blk;
}
exit_critical(state);
return NULL;
}
/* O(1): push back onto the free-list stack. Safe to call from an ISR because
* the critical section makes the push atomic with respect to pool_alloc too,
* not just with respect to another pool_free. */
void pool_free(mem_pool_t *pool, void *ptr) {
if (ptr == NULL) {
return;
}
uint32_t state = enter_critical();
pool_block_t *blk = (pool_block_t *)ptr;
blk->next = pool->free_list;
pool->free_list = blk;
pool->free_count++;
exit_critical(state);
}
#define BLOCK_SIZE 16
#define BLOCK_COUNT 4
int main(void) {
static uint8_t buffer[BLOCK_SIZE * BLOCK_COUNT];
mem_pool_t pool;
pool_init(&pool, buffer, BLOCK_SIZE, BLOCK_COUNT);
printf("after init: free_count=%zu\n", pool.free_count);
void *blocks[BLOCK_COUNT];
for (int i = 0; i < BLOCK_COUNT; i++) {
blocks[i] = pool_alloc(&pool);
printf("alloc %d -> %s, free_count=%zu\n", i, blocks[i] ? "ok" : "NULL", pool.free_count);
}
void *overflow = pool_alloc(&pool);
printf("alloc on empty pool -> %s\n", overflow == NULL ? "NULL (pool exhausted)" : "unexpected non-NULL");
pool_free(&pool, blocks[1]);
printf("after freeing blocks[1]: free_count=%zu\n", pool.free_count);
void *reused = pool_alloc(&pool);
printf("alloc after free -> %s, reused_same_slot=%s, free_count=%zu\n",
reused ? "ok" : "NULL",
reused == blocks[1] ? "yes" : "no",
pool.free_count);
return 0;
}
Output
after init: free_count=4
alloc 0 -> ok, free_count=3
alloc 1 -> ok, free_count=2
alloc 2 -> ok, free_count=1
alloc 3 -> ok, free_count=0
alloc on empty pool -> NULL (pool exhausted)
after freeing blocks[1]: free_count=1
alloc after free -> ok, reused_same_slot=yes, free_count=0
Compiled with clang -Wall -Wextra -O2 and run unchanged: matches the trace above exactly.
I also built an adversarial harness against the version that protects only pool_free (both the original eager-init design and a first attempt at fixing just the O(1) init issue): split pool_alloc's read-then-write into its two halves, run the first half, inject a pool_free call in between (standing in for an ISR), then run the second half. In both unprotected variants, the ISR-freed block came back unreachable from the free list and free_count permanently disagreed with the list's true length. Against the version above, where the critical section covers the whole of pool_alloc including both branches, that injection point no longer exists, there is no unprotected window to fire the ISR into, and the same harness run end-to-end reproduces the trace above with no lost blocks and free_count staying in sync.
Key points
- The free-list stack lives inside the blocks themselves once they've been freed at least once, no separate metadata array for that path, so overhead is one pointer's worth of waste per freed-and-not-yet-reallocated block.
- The trick that makes init O(1): a never-touched block doesn't need an explicit "next" pointer at all, since its address is
pool_start + index * block_sizefor the next never-touched index, computable without ever visiting the block. Only a block that has actually been freed needs a real intrusive-list write, and that write happens inpool_free, notpool_init. pool_allocnever touches memory outside the block it returns, and never zeroes it, callers shouldn't assume freshly allocated memory is zeroed.- Both
pool_allocandpool_freeneed the critical section, not justpool_free. The spec only calls outpool_freerunning from an ISR, butpool_alloc's pop (from either its free-list branch or its lazy-counter branch) is a non-atomic read-then-write on main context; an ISR firing mid-pop and callingpool_freecan still corrupt the list even thoughpool_allocitself never runs in interrupt context. "Which function runs in the ISR" is the wrong question, "can this function's multi-step access to shared state be interrupted by another mutator of that same state" is the right one.
Complexity
pool_init: O(1), a fixed number of field writes, independent of block_count. pool_alloc and pool_free: O(1) worst case each, no search, no loop, no fragmentation accounting, all three requirements from the spec. Space overhead: zero beyond the buffer itself and the handful of pool-struct scalars, freed blocks are threaded through the buffer itself exactly as before. The critical sections add a small, bounded constant-time cost (disable/enable interrupts) to both operations, not a complexity-class change.
Edge cases
- Allocating from an empty pool (free-list stack empty and
num_never_touched == block_count) returnsNULLrather than blocking or asserting, callers must check it, shown above as "pool exhausted." - Freeing
NULLis a no-op, guarded explicitly rather than crashing. block_sizemust be at leastsizeof(pool_block_t)(one pointer) or the free-list threading corrupts adjacent blocks once a block is freed, a real-world version would assert this inpool_init.- Freeing the same pointer twice (double free) isn't detected here, it would silently push the block onto the free-list stack twice, corrupting it on the next two allocations; a debug build could guard against this with a magic-byte check per block.
- The critical-section duration on
pool_alloc/pool_freeis fixed and tiny (a handful of instructions), so this design doesn't create meaningful interrupt latency, but it's worth knowing that any future change that grows what happens inside the critical section (e.g. adding per-block bookkeeping writes) grows worst-case interrupt-disable time too.
Explain the difference between stack and heap memory in an embedded system. Discuss deterministic behavior, typical sizes on microcontrollers, risks of dynamic allocation such as fragmentation and non-determinism, how interrupts and recursion affect stack usage, and strategies to avoid heap allocations in firmware.
Sample Answer
Definitions
The stack is a last-in-first-out region for function call frames: local variables, return addresses, saved registers. It grows and shrinks automatically as functions call and return, allocation and deallocation are an O(1) pointer move, and a variable's lifetime is exactly its enclosing function's scope. The heap is a region for allocations whose size or lifetime isn't known at compile time (malloc/free, new/delete), managed by an allocator that has to search for space matching each request.
Typical sizes on microcontrollers
Total RAM on a small MCU might be 32 to 256 KB. The stack is usually a fixed region reserved by the linker script, commonly a few KB (2-8 KB is typical on small parts). Heap, if used at all, gets whatever's left, and a lot of bare-metal firmware avoids the general heap entirely.
Deterministic behavior
Stack allocation is deterministic: fixed cost, fixed location, automatically freed in reverse order at function return. Heap allocation is generally non-deterministic in embedded contexts, a general-purpose allocator has to walk free lists or find a fitting block, and that search time varies with the current fragmentation state, a real problem for hard real-time deadlines, not just a style preference.
Risks of dynamic allocation
- Fragmentation: repeated allocation and freeing of different sizes leaves the heap full of small gaps that in total have enough space but no single block big enough for the next request, and this gets worse the longer firmware runs without a reboot.
- Non-determinism: an unbounded allocation time is incompatible with hard real-time deadlines.
- No OOM (out-of-memory) recovery story: many small MCUs have no OS-level mechanism to reclaim memory when it runs low, and
mallocreturning NULL might not even be checked everywhere.
Interrupts and recursion
Every function call, including one an interrupt causes, pushes a new frame onto the stack. If an interrupt fires while deep in a recursive call chain, its frame stacks on top of whatever was already there, all on the same stack unless the RTOS (real-time operating system, a scheduler built to guarantee deadlines) gives each task or interrupt level its own. Recursion is especially dangerous because its depth is often data-dependent (a recursive parser's depth depends on the input), so worst-case stack usage isn't statically boundable the way straight-line code is, an untested deep call can silently overrun the stack region into adjacent memory.
Strategies to avoid heap allocation in firmware
- Prefer static or global allocation sized at compile time.
- Where dynamic-feeling behavior is genuinely needed, use a fixed-size memory pool allocator instead of general
malloc/free, bounded and deterministic. - Avoid recursion, or bound its depth explicitly and test the worst case.
- Check actual stack usage against the reserved size using toolchain support (e.g. GCC's
-fstack-usage) rather than assuming it fits.
Compare using C++ versus C in constrained embedded systems. Discuss impacts on binary size, runtime features such as exceptions and RTTI, zero-cost abstractions and templates, inlining and code bloat, and developer productivity. Which C++ features are typically safe for microcontroller firmware and which to avoid?
Sample Answer
Framing
The real trade-off isn't "C is small, C++ is bloated," it's that C++ gives you more rope: both to write tighter code via zero-cost abstractions, and to accidentally bloat things via unconstrained templates, a heap-using standard library, or pervasive virtual dispatch.
Binary size
A naive C++ program can pull in runtime support code even for simple cases, though modern toolchains with -fno-exceptions -fno-rtti and careful linking close most of that gap. The real size risk in practice isn't the language baseline, it's which features you opt into.
Exceptions and RTTI
Exception-handling machinery (unwind tables, landing pads) adds real flash footprint even in code paths that never throw, and unwinding itself has non-deterministic timing, unacceptable for hard real-time code. Standard embedded practice disables exceptions entirely (-fno-exceptions) and uses return codes or error enums instead. RTTI (runtime type information, dynamic_cast, typeid) similarly adds per-class metadata and code size for a feature embedded code rarely needs, commonly disabled with -fno-rtti.
Zero-cost abstractions and templates
A templated fixed-size array class with no virtual calls compiles down to the same instructions as the raw array equivalent, that's the zero-cost promise, you don't pay for what you don't use, and what you do use compiles as tight as hand-written C. The catch: template instantiation happens per unique type or parameter combination, so a generic container used with five different element types generates five separate code paths. That's code bloat from overuse of generics across many types, distinct from the abstraction itself being free.
Inlining and code bloat
Aggressive inlining trades code size for speed, more a general compiler-flag concern than a C-versus-C++ one, but C++'s heavier use of small wrapper functions (getters, operator overloads) creates more inlining opportunities, and more places where a missed inline leaves real call overhead behind. Worth checking generated assembly on a size-critical build rather than assuming.
Developer productivity
C++ genuinely helps here: RAII (resource acquisition is initialization, tying cleanup to object lifetime) eliminates a class of manual-cleanup bugs, forgetting to release a peripheral or free a pool block on an error path. Stronger typing and templates catch more mistakes at compile time than C's weaker type system, and namespaces or classes organize a large codebase better than C's flat function namespace.
Which features are typically safe on MCU (microcontroller unit) firmware
RAII for deterministic resource management, templates for zero-cost generic code (watch instantiation count), constexpr for compile-time computation (moves work from runtime to build time, genuinely free), and a curated standard-library subset avoiding default heap allocation, many embedded C++ projects avoid std::vector, std::string, and std::map entirely, or use fixed-capacity alternatives.
Which to avoid
Exceptions and RTTI, the standard-library pieces that heap-allocate by default, virtual dispatch used pervasively (each call adds an indirect jump through a vtable, and the vtable itself costs flash per polymorphic class), and heavy multiple inheritance or template metaprogramming that makes generated code size hard to predict.
Closing judgment
The decision is really whether the team can hold a disciplined C++ subset, embedded C++ style guides exist specifically for this. If not, or the target's toolchain is old or weak, plain C stays the safer default.
An algorithm you rely on runs in O(n^2) time over a dataset that keeps growing, but your target device only has 32KB of RAM. How would you rework it to fit, and what would guide your choice of approach?
Sample Answer
Framing
This bundles two separate problems: an unbounded RAM ceiling (32 KB won't hold the whole growing dataset indefinitely) and an unbounded time cost (O(n^2) work growing with n). They need different fixes, but on a constrained device they interact, a fix for one alone can still fail on the other.
If the O(n^2) shape comes from all-pairs comparison
Naive duplicate detection or a naive nearest-neighbor scan comparing every element to every other element is the classic source of O(n^2). The standard time fix is a better algorithm for the same problem: sort once (O(n log n)) and compare only adjacent elements, or use a hash-based approach for exact matches (O(n) average), whichever matches what's actually being computed.
If holding the full dataset is what's actually blowing the 32 KB budget
Stop assuming full materialization is possible at all. Process in a streaming or windowed fashion, keeping only a bounded summary or a bounded window of recent elements (a fixed-size ring buffer) rather than the whole growing set. Some algorithms fundamentally need to see all pairs across the entire unbounded history, exact duplicate detection forever, for instance, and if that genuinely can't fit in 32 KB, the honest move is redefining the problem in terms of a bounded window ("duplicates within the last N items"), a real product trade-off to surface explicitly, not something to silently approximate.
Approximate structures as a middle ground
If exact correctness over the full growing set isn't strictly required, a fixed-memory probabilistic structure, a Bloom filter for approximate membership or duplicate checks, gives bounded RAM regardless of how large the dataset grows, at the cost of a known false-positive rate. This directly targets the "dataset keeps growing but RAM doesn't" mismatch in a way plain algorithm-swapping doesn't.
External storage as a last resort
If the device has flash beyond the 32 KB of RAM, spill the working set there and read back only what's needed for each step, a merge-sort-style external algorithm, trading I/O time (flash latency and write endurance) for RAM. Whether this is viable depends on flash wear characteristics and whether the access pattern is sequential enough to suit flash's block-oriented nature.
What guides the choice
The actual required correctness semantics, does the answer really need the full unbounded history, or is a recent window acceptable, how tolerant the application is of approximation (a monitoring or dedup use case may tolerate a Bloom filter's false positives, a billing or safety-critical one may not), and whether flash or external storage is even available to trade against RAM, on the smallest MCUs it may not be.
On a multi-core embedded SoC with a shared L2 cache and several DMA engines, design memory allocation and synchronization strategies for three tasks: real-time audio processing (core A), logging/telemetry aggregation (core B), and network stack (core C). Goals: minimize audio latency, avoid L2 thrashing, and ensure DMA coherency. Describe buffer placement, lock granularity, cache management, and DMA buffer policies.
Sample Answer
Direct answer
Keep the real-time audio path out of the shared L2 (level-2) cache entirely, in fast core-local memory, so it never contends for L2 capacity with the other two tasks; hand audio samples from the interrupt to core A through a lock-free single-producer, single-consumer queue; put logging and networking on ordinary L2-backed shared memory with fine-grained per-queue locks; and treat every DMA (direct memory access) buffer with explicit cache clean and invalidate operations, since nothing guarantees the caches are automatically coherent with the DMA engines.
Structured elaboration
Buffer placement.
- Real-time audio (core A): allocate from on-chip TCRAM (tightly-coupled RAM, a small SRAM block wired directly to the core's local bus rather than through the shared L2) or a per-core private memory if the SoC provides one. Use small circular ring buffers, sized to comfortably fit that local memory, for double or triple buffering so DMA transfers can be pipelined.
- Network stack (core C): page-aligned buffers in the shared L2-backed DRAM, managed by a slab allocator (an allocator that pre-carves memory into fixed-size chunks to avoid fragmentation) sized to typical packet MTUs (maximum transmission unit, the largest packet size the network link allows), to keep fragmentation low.
- Logging and telemetry (core B): shared L2, but in a distinct memory region or cache color from the network buffers, so a burst of logging traffic does not evict the audio or network working sets.
Cache management and DMA coherency. Unless the SoC has a hardware-coherent DMA path, the CPU caches and the DMA engines see different views of memory and you must maintain that manually:
- CPU-to-device (e.g. audio samples handed to an output DMA): clean the D-cache (data cache) lines covering the buffer, pushing dirty CPU-cached data out to memory, before starting the DMA transfer.
- Device-to-CPU (e.g. network packets DMA'd in from the MAC): invalidate the CPU's D-cache lines covering the buffer after the DMA completes, so the CPU's next read fetches the fresh data from memory instead of a stale cache line.
- Align every DMA-visible buffer to the cache line size and round clean/invalidate operations up to full cache lines; operating on a partial line risks leaving stale bytes at the edges.
- Wrap this in driver helper functions (the same idea as Linux's
dma_map_single/dma_unmap_single) so every call site gets the maintenance right instead of hand-rolling it per buffer.
Synchronization and lock granularity.
- Audio path: a lock-free single-producer, single-consumer ring buffer between the DMA-completion interrupt and core A, using atomic pointer updates with acquire/release memory ordering (a guarantee that a reader performing the acquire sees every write the producer made before its matching release). No mutex on this path; a blocked audio core is an audible glitch.
- Logging and network paths: per-queue spinlocks or lock-free multi-producer queues are fine here, since neither has a hard real-time deadline; protect shared allocators with per-core free lists to cut contention further.
- Give the audio core's ISR (interrupt service routine) the highest interrupt priority so it always preempts logging and network work.
L2 thrash mitigation.
- Keep the audio working set small enough to live entirely in TCRAM or L1, so it never touches L2 in the first place; that is the strongest form of thrash avoidance because there is nothing left to evict.
- Use cache coloring (assigning buffers to specific address ranges so two tasks' data is guaranteed to land in different cache sets and can't evict each other) or allocator-aware placement to keep the network and logging working sets from overlapping in the same L2 sets, if the SoC exposes that control.
- Where available, use hardware memory-QoS (quality of service: prioritized access to a shared resource) or priority settings to bias L2 arbitration toward the audio core's accesses (relevant mainly for any audio metadata that does live in shared memory).
DMA buffer policies. Make buffer ownership explicit and single-directional at any moment: the DMA completion callback marks a buffer safe for the CPU to touch (after invalidate), and the CPU marks it safe for the next DMA transfer (after clean); never let both sides assume they own a buffer at the same time.
The topology looks like this:
flowchart LR
subgraph CoreA["Core A: audio ISR, real-time"]
TCRAM["Tightly-coupled RAM: audio ring buffers"]
end
subgraph CoreB["Core B: logging / telemetry"]
LOGQ["Per-core log queue"]
end
subgraph CoreC["Core C: network stack"]
NETQ["Slab-allocated packet pool"]
end
L2["Shared L2 cache + DRAM"]
DMA["DMA engines"]
CODEC["Audio codec"] --> DMA
NIC["Network MAC"] --> DMA
DMA -- clean and invalidate --> L2
TCRAM -. isolated from .- L2
LOGQ --> L2
NETQ --> L2
Worked example
Size the audio ring buffer from a latency budget instead of guessing. Say the audio path is 48kHz, 16-bit, stereo, and the budget is 4ms of buffering:
- Samples per channel in 4ms: 48,000 Hz * 0.004 s = 192 samples.
- Bytes per stereo sample pair: 2 bytes/sample * 2 channels = 4 bytes.
- One buffer: 192 * 4 = 768 bytes.
- Double-buffered (so DMA can fill the next buffer while core A drains the current one): 768 * 2 = 1,536 bytes.
That easily fits inside a typical tens-of-kilobytes TCRAM block with a wide margin left for the rest of the audio pipeline, which is the point of pulling this path out of shared L2 in the first place: the real-time working set is small and bounded, so it should live somewhere no other task can evict it from.
Trade-offs & pitfalls
- Isolating audio into core-local memory only helps if that memory actually exists and is large enough; on an SoC without private per-core SRAM, you are forced to fall back to careful L2 cache coloring instead, which is weaker.
- Skipping a cache clean or invalidate does not corrupt memory content, it makes the CPU's view diverge from the DMA engine's view intermittently, which looks exactly like a rare race condition and is correspondingly painful to debug.
- Fine-grained locks on the network and logging paths reduce contention but add per-lock overhead; if profiling shows contention is actually low, a single coarser lock with less bookkeeping may be simpler and just as fast.
- Cache coloring support, and how coherent the DMA engines are with the caches, both vary a lot by SoC vendor; verify the specific chip's TRM (technical reference manual) rather than assuming either capability exists.
Unlock Full Question Bank
Get access to all 9 Performance Optimization for Constrained Devices interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.