Search code examples
cmqttpaho

How to reduce the number of else if in paho mqtt callback function with c?


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
    }
}

Solution

  • 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:

    • either through a sorted table of constant strings which you can binary search through, or
    • as a hash table of strings

    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.