I am using the PAHO mqtt asynchronous function
to subscribe to topics, but I found a problem. When I receive and parse topics in the callback function messageArrived
, I need to write a lot of else if
to judge whether it is the corresponding topic. If so, I subscribe to many topics, then the topics written after else if
will be implemented relatively slowly because they need to be compared one by one. And because topicname is char type, so I can't use switch... Case...
, what's your good idea
rc = MQTTAsync_setCallbacks(MqttClient, (VOID*)MqttClient, connlost, messageArrived,
deliveryComplete);
...
INT32 messageArrived(VOID *context, CHAR *topicName, INT32 topicLen, MQTTAsync_message *message)
{
if (strcmp(topicName, TOPIC1) == 0)
{
//do something
}
else if (strcmp(topicName, TOPIC2) == 0)
{
//do something
}
...
// many 'else if'
...
else if (strcmp(topicName, TOPICn) == 0)
{
//do something
}
}
If you have a large amount of possible strings to check for, you need to change the whole algorithm if you want it to become more efficient. There's two common ways to implement this efficiently:
The binary search will outperform the hash table up to a certain amount of strings, after which the hash table will become the more efficient.