Performance difference between map<“string”,..>

2019-07-11 01:58发布

问题:

Possible Duplicate:
Cost of using std::map with std::string keys vs int keys?

if I have the two pieces of code:

1#:

map<unsigned int, unsigned short> ConnectedIPs;

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid)
{
    PlayerLoopList.push_back(playerid);
    char szIP[32];
    GetPlayerIp(playerid,szIP);
    unsigned short explodeIP[4];
    sscanf(szIP, " %d[^.].%d[^.].%d[^.].%d", &explodeIP[0], &explodeIP[1], &explodeIP[2], &explodeIP[3]);
    g_PlayerIP[playerid] = (explodeIP[0] + (explodeIP[1] << 8) + (explodeIP[2] << 16) + (explodeIP[3] << 24));
    ConnectedIPs[g_PlayerIP[playerid]] += 1;
    if(ConnectedIPs[g_PlayerIP[playerid]] >= g_max_ip)
    {
        Report(playerid,CHECK_IPFLOOD);
    }
    return true;
}

2#:

map<char*, unsigned short> ConnectedIPs;//edited from char to char*

PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid)
{
    PlayerLoopList.push_back(playerid);
    char szIP[32];
    GetPlayerIp(playerid,szIP);
    ConnectedIPs[szIP] += 1;
    if(ConnectedIPs[szIP] >= g_max_ip)
    {
        Report(playerid,CHECK_IPFLOOD);
    }
    return true;
}

would 2# be faster? This code is for counting the amount of connected players fron one ip. I think I am doing it right, or I'm not?

回答1:

I'm assuming you meant map<string, unsigned short> for the second case, otherwise it won't even compile.

Both trigger an O(log n) lookup in the map based on comparisons of keys. Comparing 32 bit integers is generally faster than comparing strings, so the first case should be faster.

I wouldn't worry about it though, unless there's profiling data showing this to have a significant impact on performance. If you do that only when the player connects, and the session tends to last "long enough", chances are this would be an insignificant optimization - and even then, switching to unordered_map will probably be more significant than changing the type of the key.



回答2:

The biggest effect is probably caused by the size of std::string. Your CPU cache can fit many more longs than std::strings.

However, I'd still choose the second option. That will work with IPv6.



标签: c++ map