可能重复: 使用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<“string”,...>之间的性能差异。和map< int,..>?
发布评论