c++ - map <"string",..> 和 map<int,..> 之间的性能差异?

标签 c++ map

<分区>

Possible Duplicate:
Cost of using std::map with std::string keys vs 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 的连接玩家数量。我认为我做对了,还是错了?

最佳答案

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

两者都会根据键的比较触发映射中的O(log n) 查找。比较 32 位整数通常比比较字符串更快,因此第一种情况应该更快。

不过我不会担心,除非有分析数据表明这会对性能产生重大影响。如果你只在玩家连接时这样做,并且 session 往往会持续“足够长”,那么这很可能是一个微不足道的优化 - 即使那样,切换到 unordered_map可能比更改 key 类型更重要。

关于c++ - map <"string",..> 和 map<int,..> 之间的性能差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11462981/

相关文章:

java - 安卓.view.InflateException : Binary XML file line #6: Error inflating class fragemnt

c++ - 使用 SDL 的智能指针

c++ - 使用毕达哥拉斯定理的碰撞检测不可靠?

c++ - 工作 C++03 代码上的 G++ (C++14) 链接器错误

haskell - Clojure 中的 mapcat 和 Haskell 中的 concatmap 有什么区别?

ios - 用户位置的自定义注释 View 不移动 map View

c++ - 欧拉项目 - 03 级

C++ 编译错误用右值 std::string 构造对象

c++ - 如何获得 std::map 的 std::set 键

c++ - 使用 std::string 作为 std::map 的键