map<“string”,...>之间的性能差异。和map< int,..>?

编程入门 行业动态 更新时间:2024-10-27 14:30:00
本文介绍了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;?

本文发布于:2023-07-15 18:10:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1112865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:差异   性能   lt   amp   map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!