Hello guys.
I know, the header is not clear enough. Let me explain the situation in detail.
I've a server which takes messages from clients, then check if the message type matches any of the existing types via if - else if(there are more than 30 else if statements)
Thinking having these many else ifs would be bad for performance, I've decided to use an std::map. Specifically this one:
std::map<std::string,boost::function<void(std::string)>
Then I've decided to compare these 2 techniques' performances.
What I have tried:
Test code for if-else takes 17 milliseconds.
std::string s = "test3";
for (int i = 0; i < 1000000; i++) {
if (s == "test1") test1("asd");
else if (s == "test2") test2("asd");
else if (s=="test3") test3("asd");
}
Test code for std::map takes 30 milliseconds.
std::map<std::string, boost::function<void(std::string)>> testmap
{
{"test1",boost::bind(&TcpServer::test1, this, _1) },
{"test2",boost::bind(&TcpServer::test2, this, _1) },
{"test3",boost::bind(&TcpServer::test3, this, _1) }
};
std::string s="test3";
for (int i = 0; i < 1000000; i++) {
testmap[s]("asd");
}
Why is using std::map inefficient compared to 1 if and 2 else ifs. Especially considering I don't even check if map has the key I'm searching for, which increases the value to 49 milliseconds.