<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by A Manav Prasath on Medium]]></title>
        <description><![CDATA[Stories by A Manav Prasath on Medium]]></description>
        <link>https://medium.com/@24bt04001?source=rss-bb9eb3120fe6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8GoIAcKg78fDeUDi</url>
            <title>Stories by A Manav Prasath on Medium</title>
            <link>https://medium.com/@24bt04001?source=rss-bb9eb3120fe6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:33:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@24bt04001/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Space Complexity in IoT Devices — Low memory constraints.]]></title>
            <link>https://medium.com/@24bt04001/space-complexity-in-iot-devices-low-memory-constraints-2704159fee1b?source=rss-bb9eb3120fe6------2</link>
            <guid isPermaLink="false">https://medium.com/p/2704159fee1b</guid>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[edge-computing]]></category>
            <category><![CDATA[tinyml]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[A Manav Prasath]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 20:49:32 GMT</pubDate>
            <atom:updated>2026-10-02T20:49:32.404Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How O(1) thinking, streaming algorithms, and careful memory management keep constrained devices running</em></p><p>A desktop application can allocate a few megabytes without anyone noticing.</p><p>An IoT device may not have that luxury.</p><p>Consider an Arduino Uno with only <strong>2 KB of SRAM</strong>. A buffer that looks tiny on a laptop can consume a significant fraction of the entire memory available to the microcontroller.</p><p>This changes the way software has to be designed.</p><p>In conventional programming, developers often focus primarily on <strong>time complexity</strong>: how fast an algorithm runs as its input grows. In IoT and embedded systems, <strong>space complexity can become an equally important constraint</strong> because RAM is small, fixed, and shared by the firmware, stack, buffers, and runtime.</p><p>A useful mindset is:</p><blockquote><strong><em>On a server, memory can often be scaled.<br>On a microcontroller, memory is usually a fixed budget.</em></strong></blockquote><p>This article explores how space complexity affects IoT software and how practical techniques such as <strong>streaming algorithms, bounded buffers, fixed-width data types, static allocation, and model quantization</strong> can reduce memory usage.</p><p>The central idea is simple:</p><blockquote><strong><em>Store less. Bound what you store. Measure everything.</em></strong></blockquote><h3>What Does Space Complexity Actually Mean?</h3><p>Space complexity describes how the memory requirements of an algorithm change as the input size increases.</p><p>For example:</p><ul><li><strong>O(1)</strong> means the extra memory remains constant as the input grows.</li><li><strong>O(n)</strong> means memory grows linearly with the input size.</li><li><strong>O(k)</strong> means memory depends on a fixed parameter (k), such as a fixed-size window.</li></ul><p>A simple example is storing sensor readings.</p><p>Suppose a device stores (n) floating-point temperature readings:</p><p><strong>Memory = n × sizeof(float)</strong></p><p>If a typical float occupies 4 bytes:</p><p><strong>Memory = 4n bytes</strong></p><p>For (n = 1000):</p><p><strong>1000 × 4 = 4000 bytes ≈ 3.9 KB</strong></p><p>On a desktop, this is insignificant.</p><p>On an Arduino Uno with only <strong>2 KB of SRAM</strong>, it is already too large.</p><blockquote><strong><em>Important:</em></strong><em> O(1) does not mean “uses very little memory.” It only means memory usage does not grow with input size. An algorithm using 8 bytes and another using 200 KB can both be O(1).</em></blockquote><p>This distinction matters greatly in embedded systems because both the <strong>growth rate</strong> and the <strong>absolute memory footprint</strong> matter.</p><p>A theoretically efficient algorithm can still be impossible to deploy if its fixed memory requirement is larger than the device’s available RAM.</p><h3>The IoT Memory Budget</h3><p>Microcontrollers typically divide memory into several areas, each serving a different purpose.</p><p>Here are some representative examples of memory available on common microcontroller platforms:</p><ul><li><strong>Arduino Uno (ATmega328P):</strong> 2 KB SRAM, 32 KB Flash</li><li><strong>STM32F103C8:</strong> 20 KB SRAM, up to 64 KB Flash</li><li><strong>nRF52832:</strong> 64 KB SRAM, 512 KB Flash</li><li><strong>ESP32:</strong> ~520 KB SRAM, 4 MB typical module Flash</li></ul><p><em>Exact memory specifications depend on the specific microcontroller, variant, and module.</em></p><p>Three aspects of the memory system are particularly important.</p><h3>Flash</h3><p>Flash is non-volatile memory and is commonly used for:</p><ul><li>Program code</li><li>Read-only constants</li><li>Firmware</li><li>Lookup tables</li></ul><p>Flash is often much larger than SRAM.</p><h3>SRAM</h3><p>SRAM is volatile memory and is commonly used for:</p><ul><li>Global and static variables</li><li>Runtime buffers</li><li>Stack</li><li>Heap allocations</li><li>Temporary data</li></ul><p>For many microcontrollers, <strong>SRAM is the critical resource when it comes to space complexity</strong>.</p><h3>Stack and Heap</h3><p>The stack and heap share the available SRAM according to the architecture and runtime environment.</p><p>The <strong>stack</strong> is used for function calls, local variables, return information, and other temporary state.</p><p>The <strong>heap</strong> is used for dynamic allocation through mechanisms such as malloc() and free().</p><p>Excessive stack or heap usage can result in allocation failures, memory corruption, or unexpected resets.</p><blockquote><strong><em>The important point:</em></strong><em> your algorithm does not get the entire SRAM to itself. Global variables, buffers, the stack, heap, and runtime components all compete for the same limited memory budget.</em></blockquote><h3>Think in Auxiliary Space</h3><p>In algorithm analysis, space complexity is often discussed as <strong>auxiliary space</strong>: the additional memory used by an algorithm beyond the input itself.</p><p>For IoT devices, a useful design goal is:</p><blockquote><strong><em>Push working memory toward O(1) or a small, fixed O(k).</em></strong></blockquote><p>This leads to one of the most useful rules in embedded programming:</p><blockquote><strong><em>Process streams instead of storing streams.</em></strong></blockquote><p>Sensors naturally produce data as a continuous stream:</p><p>x₁, x₂, x₃, ... , xₙ</p><p>A conventional approach might store these readings first and process them later. That means memory usage grows as more data arrives.</p><p>A streaming approach processes each reading as it arrives and keeps only the state necessary to continue the computation.</p><p>Instead of:</p><p><strong>Sensor → Store everything → Process</strong></p><p>we aim for:</p><p><strong>Sensor → Process → Discard</strong></p><p>The difference may seem small in a desktop application, but on a microcontroller with only a few kilobytes of RAM, it can determine whether the application fits in memory at all.</p><h3>Example 1: Moving Average</h3><p>A common IoT task is calculating the average of recent sensor readings.</p><p>A <strong>Simple Moving Average (SMA)</strong> over a window of (n) readings is:</p><p><strong>SMA = (x₁ + x₂ + … + xₙ) / n</strong></p><p>A straightforward implementation needs to store the readings that belong to the window. As the window size increases, the required memory also increases.</p><p>For example, storing 128 floating-point samples requires:</p><p><strong>128 × 4 bytes = 512 bytes</strong></p><p>That may not sound like much, but on a microcontroller with only a few kilobytes of SRAM, every byte matters.</p><h3>Using an Exponential Moving Average</h3><p>If the application does not require an exact sliding-window average, an <strong>Exponential Moving Average (EMA)</strong> can be used instead.</p><p>The update equation is:</p><p><strong>EMAₜ = αxₜ + (1 − α)EMAₜ₋₁</strong></p><p>Here, α controls how strongly the newest measurement affects the result.</p><p>A simple implementation is:</p><pre>static float ema = 0.0f;<br>const float alpha = 0.1f;</pre><pre>float update_ema(float sample)<br>{<br>    ema = alpha * sample<br>        + (1.0f - alpha) * ema;</pre><pre>    return ema;<br>}</pre><p>Unlike the simple moving average, this implementation does not need to store the previous 128, 256, or 1,000 samples.</p><p>It only keeps the <strong>current sample and the previous EMA value</strong>.</p><p>Therefore, its additional memory usage is:</p><p><strong>O(1)</strong></p><p>The important point is that EMA is <strong>not equivalent to a simple moving average</strong>. We are changing the algorithm to reduce memory usage.</p><p>For many sensor-filtering applications, that trade-off can be worthwhile: instead of storing an entire history, the device maintains a compact summary of the data it has already seen.</p><h3>Example 2: Running Mean and Variance</h3><p>Suppose an IoT device needs to detect unusual sensor behavior.</p><p>One approach would be to store every measurement and calculate the statistics later. However, storing all observations requires memory that grows with the number of samples.</p><p>That gives us:</p><p><strong>O(n) space</strong></p><p>A better approach is to update the statistics as each sample arrives.</p><h3>Welford’s Algorithm</h3><p><strong>Welford’s algorithm</strong> calculates a running mean and variance without storing the complete history of observations.</p><p>The algorithm maintains only three pieces of information:</p><ul><li>The number of samples seen</li><li>The current mean</li><li>An accumulated value used to calculate variance</li></ul><p>In C, this can be implemented as:</p><pre>#include &lt;stdint.h&gt;</pre><pre>typedef struct {<br>    uint32_t n;<br>    float mean;<br>    float m2;<br>} Stats;</pre><pre>void stats_update(Stats *s, float x)<br>{<br>    s-&gt;n++;</pre><pre>    float delta = x - s-&gt;mean;<br>    s-&gt;mean += delta / s-&gt;n;<br>    s-&gt;m2 += delta * (x - s-&gt;mean);<br>}</pre><pre>float stats_variance(const Stats *s)<br>{<br>    if (s-&gt;n &lt;= 1)<br>        return 0.0f;</pre><pre>    return s-&gt;m2 / (s-&gt;n - 1);<br>}</pre><p>The important property is that the algorithm stores only its <strong>current statistical state</strong>, rather than the complete history of measurements.</p><p>For common 32-bit representations, the structure requires approximately:</p><p><strong>4 bytes (</strong><strong>uint32_t) + 4 bytes (</strong><strong>float) + 4 bytes (</strong><strong>float) = 12 bytes</strong></p><p>And that memory requirement remains constant even if the device processes thousands or millions of samples.</p><p>Therefore:</p><p><strong>O(1) auxiliary space</strong></p><p>This makes running statistics useful for applications such as:</p><ul><li>Sensor anomaly detection</li><li>Predictive maintenance</li><li>Environmental monitoring</li><li>Industrial IoT</li></ul><p>The device can continuously analyze incoming data without filling its RAM with historical measurements.</p><h3>When You Actually Need a Buffer</h3><p>Not every algorithm can avoid storing history.</p><p>Some workloads genuinely need access to a window of previous samples. Examples include <strong>FFT processing, median filtering, batch transmission, sensor fusion, and audio processing</strong>.</p><p>In these situations, the goal is not always to achieve (O(1)) space. Instead, the goal is to <strong>bound the memory usage</strong>.</p><p>A useful pattern for this is a <strong>fixed-size ring buffer</strong>.</p><p>A ring buffer stores a fixed number of recent values. When the buffer becomes full, new values overwrite the oldest ones.</p><p>For example:</p><pre>#include &lt;stdint.h&gt;</pre><pre>#define WINDOW 16</pre><pre>typedef struct {<br>    int16_t data[WINDOW];<br>    uint8_t head;<br>    uint8_t count;<br>} Ring;</pre><pre>void ring_push(Ring *r, int16_t value)<br>{<br>    r-&gt;data[r-&gt;head] = value;</pre><pre>    r-&gt;head = (r-&gt;head + 1) % WINDOW;</pre><pre>    if (r-&gt;count &lt; WINDOW)<br>        r-&gt;count++;<br>}</pre><p>The memory requirement can be expressed as:</p><p><strong>Memory = k × sizeof(sample) + O(1)</strong></p><p>where (k) is the fixed window size.</p><p>For a 16-sample window using int16_t:</p><p><strong>16 × 2 bytes = 32 bytes</strong></p><p>Using float instead would require:</p><p><strong>16 × 4 bytes = 64 bytes</strong></p><p>So simply choosing a smaller representation cuts the buffer’s memory usage in half.</p><p>The key idea is that the memory requirement depends on the <strong>fixed window size</strong>, not on the total number of samples processed over the lifetime of the device.</p><p>This gives us a practical middle ground:</p><blockquote><strong><em>You do not always need O(1) space. Sometimes O(k) is the right answer — as long as k is known and bounded.</em></strong></blockquote><h3>Data Types Matter More Than They Look</h3><p>In embedded systems, data types are not merely a programming-style choice.</p><p>They directly affect how much memory your application consumes.</p><p>Suppose a device needs to store 1,000 integer sensor values.</p><p>Using 32-bit integers:</p><p><strong>1,000 × 4 bytes = 4,000 bytes</strong></p><p>Using 16-bit integers:</p><p><strong>1,000 × 2 bytes = 2,000 bytes</strong></p><p>Using 8-bit integers:</p><p><strong>1,000 × 1 byte = 1,000 bytes</strong></p><p>That is a difference of several kilobytes from a single design decision.</p><p>The correct data type depends on the range of values your application actually needs. There is no benefit in using a 32-bit variable to store a value that can safely fit inside 8 or 16 bits.</p><h3>Use Fixed-Width Types</h3><p>Instead of assuming that int has the same size on every microcontroller, embedded software often uses fixed-width integer types such as:</p><pre>uint8_t<br>int16_t<br>uint32_t<br>int32_t</pre><p>For example:</p><pre>uint16_t temperature;<br>int16_t sensor_value;<br>uint8_t device_state;</pre><p>These types make the required numeric range explicit and make the expected storage size much clearer.</p><p>This becomes particularly useful when code is moved between different architectures.</p><h3>Bit Packing</h3><p>Sometimes even a byte per value is unnecessary.</p><p>Imagine that a device needs to maintain eight binary states:</p><p>b₀, b₁, b₂, ... , b₇</p><p>Each state only has two possible values: 0 or 1.</p><p>Instead of storing each state as a separate larger variable, the eight states can be packed into a single byte:</p><pre>uint8_t flags = 0;</pre><pre>flags |= (1U &lt;&lt; 0);  // Set flag 0<br>flags |= (1U &lt;&lt; 3);  // Set flag 3</pre><pre>if (flags &amp; (1U &lt;&lt; 3)) {<br>    // Flag 3 is active<br>}</pre><p>A single byte contains eight individual bits, so eight Boolean states can be represented in just <strong>1 byte</strong>.</p><p>Bit packing can provide significant savings when many flags or small values need to be stored. The trade-off is that the code can become less readable and more difficult to maintain.</p><blockquote><strong><em>Use the smallest practical representation, but do not optimize blindly.</em></strong><em> The type still needs to provide enough range and precision for the application.</em></blockquote><p>On a resource-constrained device, a few bytes saved in one structure may seem insignificant. Across hundreds of variables, however, those savings can become a meaningful part of the overall SRAM budget.</p><h3>Avoid Dynamic Allocation When Possible</h3><p>Dynamic memory allocation is useful in many software systems, but it requires extra caution on small and long-running embedded devices.</p><p>Functions such as malloc() and free() allocate and release memory from the heap at runtime. Frequent allocation and deallocation can lead to <strong>heap fragmentation</strong> over time.</p><p>For example, a device might still have enough total free RAM but fail to allocate a large block because the available memory is divided into smaller fragments.</p><p>This can be especially problematic for IoT devices that are expected to run continuously for days, months, or even years.</p><p>When the required buffer size is known in advance, a fixed allocation is often easier to reason about:</p><pre>#define BUFFER_SIZE 128</pre><pre>uint8_t buffer[BUFFER_SIZE];</pre><p>Instead of repeatedly allocating temporary buffers:</p><pre>uint8_t *buffer = malloc(BUFFER_SIZE);</pre><pre>/* Use buffer */</pre><pre>free(buffer);</pre><p>A statically allocated buffer has a predictable memory footprint and does not depend on the current state of the heap.</p><p>There is also another advantage: <strong>the memory budget is visible at compile time</strong>.</p><p>You already know that:</p><p><strong>128 × 1 byte = 128 bytes</strong></p><p>will be reserved for the buffer.</p><p>This does not mean dynamic allocation should never be used. On larger devices or in applications where memory requirements genuinely change at runtime, it can be appropriate.</p><p>The principle is:</p><blockquote><strong><em>When memory requirements are known and bounded, prefer predictable allocation over unnecessary runtime allocation.</em></strong></blockquote><p>On resource-constrained systems, predictability is often just as valuable as saving a few bytes.</p><h3>Keep Constants Out of RAM When the Platform Allows It</h3><p>Not all data needs to be modified at runtime.</p><p>Large lookup tables, strings, calibration data, and other read-only information can consume valuable RAM depending on the microcontroller, compiler, and toolchain.</p><p>On AVR-based systems such as the ATmega328P, mechanisms such as PROGMEM can explicitly place constant data in program memory instead of SRAM.</p><p>For example:</p><pre>#include &lt;avr/pgmspace.h&gt;</pre><pre>const uint8_t table[] PROGMEM = {<br>    0, 4, 8, 12, 16, 20, 24, 28<br>};</pre><p>This can be useful for applications containing large lookup tables or fixed datasets that need to remain available during execution but never need to be modified.</p><p>However, memory behavior differs across architectures.</p><p>A declaration such as const does not universally guarantee that the data will consume no SRAM. Some platforms and toolchains automatically place read-only data in flash, while others may require additional attributes or platform-specific mechanisms.</p><p>The important question is therefore not simply:</p><p><strong>“Is this variable constant?”</strong></p><p>but:</p><p><strong>“Where does my toolchain actually place this data?”</strong></p><blockquote><strong><em>Understand the memory model of the specific MCU and compiler you are using instead of assuming that every constant automatically lives in flash.</em></strong></blockquote><p>On a memory-constrained device, moving even a few hundred bytes of read-only data out of SRAM can make room for buffers, stack space, or other runtime requirements.</p><h3>Recursion Has a Memory Cost</h3><p>Recursion is a useful technique in algorithms, but every recursive function call consumes stack memory.</p><p>Each call creates a new stack frame containing information such as local variables, parameters, and the return address.</p><p>If the maximum recursion depth is (d), the auxiliary space is generally:</p><p><strong>O(d)</strong></p><p>On systems with abundant memory, this may not be a major concern.</p><p>On a microcontroller with only a few kilobytes of SRAM, however, deep recursion can consume a significant portion of the available stack and potentially lead to a <strong>stack overflow</strong>.</p><p>For example, a recursive function such as:</p><pre>void countdown(int n)<br>{<br>    if (n &lt;= 0)<br>        return;</pre><pre>    countdown(n - 1);<br>}</pre><p>creates a new function call for every value of n.</p><p>As n increases, the stack usage also increases.</p><p>When possible, the same logic can often be expressed iteratively:</p><pre>void countdown(int n)<br>{<br>    while (n &gt; 0) {<br>        n--;<br>    }<br>}</pre><p>The iterative version does not create a new stack frame for every iteration, so its additional space remains constant:</p><p><strong>O(1)</strong></p><p>This does not mean recursion is always wrong for embedded systems. If the recursion depth is small and well-bounded, it may be perfectly reasonable.</p><p>The key is to understand the memory cost before using it.</p><blockquote><strong><em>On a constrained device, every function call has a memory cost. When recursion is unnecessary, iteration often provides more predictable stack usage.</em></strong></blockquote><h3>Parse Streams, Not Entire Documents</h3><p>IoT devices frequently receive data over communication interfaces such as <strong>Wi-Fi, Bluetooth, UART, MQTT, HTTP, and LoRa</strong>.</p><p>A common memory mistake is to receive an entire payload into RAM before processing it.</p><p>For example:</p><pre>char payload[4096];</pre><p>A 4 KB buffer may already exceed the entire SRAM available on some small microcontrollers.</p><p>Even when the payload fits, the actual memory requirement can be larger than expected. Parsing a structured format such as JSON may require additional temporary structures, token storage, or duplicated strings.</p><p>Instead of loading everything into memory first, data can often be processed incrementally as it arrives.</p><p>The general idea is:</p><p><strong>Stream → Parse → Process → Discard</strong></p><p>rather than:</p><p><strong>Receive everything → Store → Process</strong></p><p>For example, instead of keeping an entire incoming message in RAM, a device can read a small portion, extract the information it needs, and immediately discard the processed portion.</p><p>This approach is especially useful when dealing with:</p><ul><li>Continuous sensor streams</li><li>Large network messages</li><li>Log data</li><li>Serial communication</li><li>Telemetry</li><li>File transfers</li></ul><p>For structured data, <strong>streaming parsers</strong> can reduce peak RAM usage compared with parsing an entire document at once.</p><p>Another option is to use a compact binary format such as <strong>CBOR</strong> when it is appropriate for the application. A more compact representation can reduce both the amount of data transmitted and the amount that needs to be buffered.</p><blockquote><strong><em>On a constrained device, the best data structure can sometimes be no data structure at all — just process the data and move on.</em></strong></blockquote><p>The goal is not necessarily to eliminate buffering completely. Instead, keep the amount of data held in memory <strong>small, predictable, and bounded</strong>.</p><h3>TinyML Makes Memory Optimization Even More Important</h3><p>Machine learning at the edge introduces another major memory consumer: <strong>the model itself</strong>.</p><p>A neural network is made up of parameters such as weights and biases. The amount of memory required to store these parameters depends heavily on their numerical representation.</p><p>A model using 32-bit floating-point parameters, commonly called <strong>FP32</strong>, requires approximately:</p><p><strong>4 bytes per parameter</strong></p><p>If the same parameters are quantized to 8-bit integers, or <strong>INT8</strong>, they require approximately:</p><p><strong>1 byte per parameter</strong></p><p>Consider a model containing 100,000 parameters.</p><h3>FP32</h3><p><strong>100,000 × 4 bytes = 400,000 bytes ≈ 390.6 KB</strong></p><h3>INT8</h3><p><strong>100,000 × 1 byte = 100,000 bytes ≈ 97.7 KB</strong></p><p>So, for the model parameters alone, moving from FP32 to INT8 provides approximately a:</p><p><strong>4× reduction in storage</strong></p><p>This is one of the reasons quantization is widely used when deploying machine-learning models on resource-constrained edge devices.</p><p>However, <strong>model size is not the same as total runtime memory usage</strong>.</p><p>An embedded ML application may also need memory for:</p><ul><li>Model weights</li><li>Activation tensors</li><li>Input and output buffers</li><li>Tensor arena</li><li>Runtime state</li><li>Stack</li><li>Sensor and communication buffers</li></ul><p>This means a model can fit comfortably in <strong>Flash</strong> while still failing during execution because its working memory requirements exceed the available <strong>SRAM</strong>.</p><blockquote><strong><em>A model fitting in Flash does not guarantee that it will fit in SRAM at runtime.</em></strong></blockquote><p>This distinction becomes especially important with frameworks such as <strong>TensorFlow Lite Micro</strong>, where the model, intermediate activations, input data, and other runtime structures must all fit within the target device’s memory budget.</p><p>The same principle from traditional embedded programming still applies:</p><p><strong>Store only what you need, use compact representations, and keep memory requirements predictable.</strong></p><p>For TinyML, however, the challenge becomes more complex because you are no longer optimizing only your application code. You are also optimizing the <strong>representation and execution of the model itself</strong>.</p><h3>A Simple IoT Memory Budget</h3><p>To understand why memory optimization matters, imagine an IoT device with:</p><p><strong>32 KB of SRAM</strong></p><p>That may sound like a reasonable amount of memory until several components begin competing for it.</p><p>A simplified memory budget could look like this:</p><p><strong>32 KB Total SRAM</strong></p><p>→ Global and static data: <strong>6 KB</strong><br>→ Sensor and network buffers: <strong>8 KB</strong><br>→ ML tensor arena: <strong>10 KB</strong><br>→ Stack and runtime headroom: <strong>8 KB</strong></p><p>These numbers are only illustrative, but they demonstrate an important principle:</p><blockquote><strong><em>The SRAM advertised in a datasheet is not a dedicated memory pool for your algorithm.</em></strong></blockquote><p>The available memory has to accommodate everything running on the device.</p><p>A useful way to think about the budget is:</p><p><strong>Available SRAM = Data + Buffers + Stack + Heap + Runtime</strong></p><p>For example, increasing a sensor buffer from 2 KB to 10 KB does not simply consume “8 KB of free memory.” Those 8 KB may have been needed for stack headroom, an ML tensor arena, or communication buffers.</p><p>This is why memory planning should happen <strong>before deployment</strong>, rather than only after the firmware starts failing.</p><p>A good embedded design therefore asks:</p><p><strong>How much memory does each component require, and how much headroom remains?</strong></p><p>That question is often more useful than simply asking whether the algorithm is theoretically (O(1)) or (O(n)).</p><h3>Measure Before You Optimize</h3><p>Memory optimization should be based on <strong>measurements rather than intuition</strong>.</p><p>A program that looks small in the source code can still produce a surprisingly large memory footprint after compilation. Libraries, global variables, buffers, alignment, stack usage, and runtime components can all contribute to the final memory consumption.</p><h3>Static Firmware Size</h3><p>For ARM embedded toolchains, a command such as:</p><pre>arm-none-eabi-size firmware.elf</pre><p>can report sections such as:</p><ul><li>text — program code and read-only data stored in the executable image</li><li>data — initialized global and static variables that occupy RAM</li><li>bss — zero-initialized global and static variables that occupy RAM</li></ul><p>The data and bss sections are particularly useful when estimating the firmware&#39;s static SRAM usage.</p><h3>Runtime Heap</h3><p>Static analysis is only part of the picture. Some systems also need to monitor heap usage while the firmware is running.</p><p>For example, on ESP32:</p><pre>size_t free_heap = ESP.getFreeHeap();</pre><p>Under FreeRTOS, heap information can also be queried using APIs such as:</p><pre>xPortGetFreeHeapSize();</pre><p>These values help identify how much heap memory remains available at runtime.</p><h3>Stack Usage</h3><p>Stack usage can be just as important as heap usage, especially when functions have large local variables or when recursion is involved.</p><p>In FreeRTOS, the following API can help monitor task stack usage:</p><pre>uxTaskGetStackHighWaterMark();</pre><p>This provides information about the minimum remaining stack space observed for a task.</p><h3>Map Files</h3><p>When memory usage is unexpectedly high, a linker map file can help identify which symbols and sections are consuming memory.</p><p>For example:</p><pre>-Wl,-Map=output.map</pre><p>A map file can reveal large arrays, global variables, library components, and other objects contributing to the firmware footprint.</p><p>The broader lesson is simple:</p><blockquote><strong><em>Do not optimize based on how the source code looks. Measure the compiled firmware and the running device.</em></strong></blockquote><p>Once you know where the memory is actually going, you can decide whether the problem is a large buffer, excessive static data, stack usage, heap fragmentation, or something else entirely.</p><p>In embedded systems, measurement turns memory optimization from guesswork into engineering.</p><h3>Space Complexity Trade-offs</h3><p>Reducing memory usage is not always free.</p><p>An optimization that saves RAM can introduce additional CPU work, reduce numerical precision, or make the code more difficult to maintain. In embedded systems, the goal is therefore not simply to minimize memory at any cost, but to find the right balance for the application.</p><h3>Space vs. Time</h3><p>Sometimes we can save memory by recomputing a value instead of storing it.</p><p>For example, caching intermediate results can reduce computation time, but the cached values occupy memory. Removing the cache can reduce RAM usage, but the device may need to perform the calculation again.</p><p>In other words:</p><p><strong>Less memory ↔ Potentially more computation</strong></p><p>For battery-powered IoT devices, this trade-off can also affect energy consumption because additional computation may require more CPU activity.</p><h3>Space vs. Accuracy</h3><p>Memory reduction can also affect the accuracy or fidelity of the result.</p><p>Replacing a Simple Moving Average with an EMA changes how historical data influences the result.</p><p>Similarly, quantizing an FP32 machine-learning model to INT8 can significantly reduce parameter storage, but it may introduce some quantization error.</p><p>Therefore:</p><p><strong>Less memory ↔ Potential loss of precision or fidelity</strong></p><p>The important question is whether the resulting accuracy is still sufficient for the application.</p><h3>Space vs. Maintainability</h3><p>Highly optimized memory layouts can make embedded software harder to understand.</p><p>Bit-packing, custom memory pools, and tightly optimized data structures may save valuable bytes, but they can also make the code more difficult to read, debug, and modify.</p><p>Therefore, optimization should be proportional to the actual constraint.</p><blockquote><strong><em>Do not optimize every byte just because you can. Optimize where measurements show a real memory bottleneck.</em></strong></blockquote><p>If a device has hundreds of kilobytes of available memory, spending hours to save a few bytes may not be worthwhile. On a device with only a few kilobytes of SRAM, however, the same optimization could make the difference between a working application and one that cannot run.</p><p>The best embedded design is not the one that uses the absolute minimum memory.</p><p>It is the one that uses <strong>enough memory to meet the requirements while leaving sufficient headroom for reliable operation</strong>.</p><h3>A Practical Checklist</h3><p>Before deploying an IoT application, it is useful to review its memory requirements systematically.</p><p>Ask yourself:</p><ol><li><strong>Can the algorithm process data as a stream instead of storing it?</strong></li><li><strong>Does every buffer have a known maximum size?</strong></li><li><strong>Can a dynamically allocated structure be replaced with static storage?</strong></li><li><strong>Am I using the smallest data type that safely represents the required range and precision?</strong></li><li><strong>Can read-only data remain in Flash instead of consuming SRAM?</strong></li><li><strong>Is recursion necessary, or can the operation be performed iteratively?</strong></li><li><strong>Can a more compact representation, such as bit packing or quantization, reduce memory usage?</strong></li><li><strong>Have I measured stack and heap usage on the actual hardware?</strong></li><li><strong>For TinyML workloads, do the model, activation memory, tensor arena, and input/output buffers all fit within the available memory?</strong></li><li><strong>Is the memory saving worth the additional CPU usage, accuracy trade-off, or code complexity?</strong></li></ol><p>These questions turn space complexity from a theoretical concept into a practical design process.</p><p>The goal is to know <strong>where the memory is going, why it is needed, and whether there is a simpler way to achieve the same result</strong>.</p><h3>Conclusion</h3><p>Space complexity is not just an academic property of an algorithm.</p><p>On an IoT device, it can determine whether the software is feasible at all.</p><p>A desktop computer can often hide inefficient memory usage behind gigabytes of RAM. A microcontroller cannot. When memory is measured in kilobytes, every buffer, variable, stack frame, and runtime component matters.</p><p>The most useful habits are therefore straightforward:</p><p><strong>Prefer streaming over storing.</strong></p><p><strong>Bound every buffer.</strong></p><p><strong>Choose data types deliberately.</strong></p><p><strong>Avoid unnecessary dynamic allocation.</strong></p><p><strong>Measure the actual firmware and runtime memory.</strong></p><p>For TinyML systems, the same philosophy extends beyond traditional algorithms. Model weights, activation tensors, tensor arenas, sensor buffers, and runtime state all compete for limited memory.</p><p>The goal is not to make every algorithm (O(1)) simply because (O(1)) sounds efficient.</p><p>The goal is to design software whose memory requirements are <strong>predictable, bounded, and compatible with the hardware budget</strong>.</p><p>That is what writing code for kilobytes really means.</p><h3>References</h3><ol><li><a href="https://www.microchip.com/"><strong>ATmega328P 8-bit AVR Microcontroller Datasheet</strong> — Microchip Technology Inc.</a></li><li><a href="https://www.st.com/resource/en/datasheet/stm32f103c8.pdf"><strong>STM32F103x8 / STM32F103xB Datasheet</strong> — STMicroelectronics.</a></li><li><a href="https://infocenter.nordicsemi.com/pdf/nRF52832_PS_v1.9.pdf"><strong>nRF52832 Product Specification</strong> — Nordic Semiconductor.</a></li><li><a href="https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf"><strong>ESP32 Series Datasheet</strong> — Espressif Systems.</a></li><li><a href="https://ai.google.dev/edge/litert/microcontrollers/overview"><strong>LiteRT for Microcontrollers</strong> — Google.</a></li><li><a href="https://doi.org/10.1080/00401706.1962.10490022"><strong>Welford, B. P.</strong>, “Note on a Method for Calculating Corrected Sums of Squares and Products,” <em>Technometrics</em>, vol. 4, no. 3, 1962.</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2704159fee1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>