地图<“string”,..>之间的性能差异并映射< int,..>? [英] Performance difference between map<"string",..> and map<int,..>?

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

问题描述


可能重复:

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

如果我有两段代码:

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

会2#快吗?
这段代码用于计算一个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?

推荐答案

我假设你的意思是 map< string,unsigned short> 为第二种情况,否则它甚至不会编译。

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

两者都触发一个O (log n)查找在地图中基于键的比较。比较32位整数通常比比较字符串更快,所以第一种情况应该更快。

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.

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

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