map<“string”,...>之间的性能差异。和map< int,..>? [英] Performance difference between map<"string",..> and map<int,..>?

查看:535
本文介绍了map<“string”,...>之间的性能差异。和map< int,..>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用std :: map和std :: string键和int键的成本?

如果我有两个代码:

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

会更快吗?
此代码用于计算一个ip连接的玩家的数量。

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?

推荐答案

我假设你的意思是

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.

我不会担心它,除非有分析数据显示这个对性能有重大影响。如果你这样做只有当播放器连接,并且会话持续足够长,很可能这是一个微不足道的优化 - 即使这样,切换到 unordered_map 可能比更改键的类型更重要。

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.

这篇关于map&lt;“string”,...&gt;之间的性能差异。和map&lt; int,..&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆