EEPROM for storing settings in Arduino - Time & Space Complexity
When using EEPROM to save settings on an Arduino, it's important to know how the time to save or read data changes as the amount of data grows.
We want to understand how the program's running time changes when storing more settings.
Analyze the time complexity of the following code snippet.
#include <EEPROM.h>
void saveSettings(int* settings, int size) {
for (int i = 0; i < size; i++) {
EEPROM.write(i, settings[i]);
}
}
This code saves an array of settings into EEPROM memory, one byte at a time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing each setting byte to EEPROM inside a for-loop.
- How many times: The loop runs once for each setting, so it repeats size times.
As the number of settings increases, the time to save them grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes to EEPROM |
| 100 | 100 writes to EEPROM |
| 1000 | 1000 writes to EEPROM |
Pattern observation: Doubling the number of settings doubles the time needed to save them.
Time Complexity: O(n)
This means the time to save settings grows directly with the number of settings you want to store.
[X] Wrong: "Writing one byte to EEPROM takes the same time no matter how many bytes I write overall."
[OK] Correct: Each byte write takes time, so writing more bytes adds up and takes longer overall.
Understanding how saving data scales helps you design efficient programs that handle settings well, a useful skill in many embedded projects.
"What if we only write to EEPROM when a setting changes? How would the time complexity change?"