Topic design patterns for IoT in IOT Protocols - Time & Space Complexity
When designing topics for IoT devices, it is important to understand how the number of topics affects system performance.
We want to know how the time to process messages grows as the number of topics increases.
Analyze the time complexity of the following topic subscription handling code.
for topic in subscribed_topics:
if incoming_message.topic == topic:
process_message(incoming_message)
break
This code checks each subscribed topic to find a match for the incoming message topic, then processes it.
- Primary operation: Looping through the list of subscribed topics.
- How many times: Up to once per subscribed topic until a match is found.
As the number of subscribed topics grows, the time to find a matching topic grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 topic checks |
| 100 | Up to 100 topic checks |
| 1000 | Up to 1000 topic checks |
Pattern observation: The number of checks grows linearly with the number of topics.
Time Complexity: O(n)
This means the time to find a matching topic grows directly with the number of subscribed topics.
[X] Wrong: "Checking topics is always fast and does not depend on how many topics there are."
[OK] Correct: Each topic must be checked one by one until a match is found, so more topics mean more checks and more time.
Understanding how topic matching scales helps you design efficient IoT systems and shows you can think about performance in real-world scenarios.
"What if the topics were stored in a hash map instead of a list? How would the time complexity change?"