首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++11速度比较/成本std::hash<std::string>等于与std::string直接在2个大字符串上相等

问c++11速度比较/成本std::hash<std::string>等于与std::string直接在2个大字符串上相等
EN

Stack Overflow用户
提问于 2013-07-26 17:07:23
回答 1查看 5.1K关注 0票数 2

嗨,我有一个关于std::散列的问题,如果我有两个大字符串进行比较,并且我愿意接受std::散列在大多数情况下是相等的,那么做下面这样的操作比直接字符串比较更符合性能吗?另外,考虑到这将在一个循环中读取一个文件,因此它将被执行几次,这是对大型文件的关注。

代码语言:javascript
复制
std::string largeString1;  // large but not huge meaning a line of text like up to lets say 500 chars 
std::string largeString2;

// is this better than then next block in terms of performance and if so by how much?
if ( std::hash<std::string>(largeString1) == std::hash<std::string>(largeString2) )
{
// true logic
}

// is this a lot slower than the previous
if ( largeString1 == largeString2 )
{
// true logic
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-26 17:16:44

代码语言:javascript
复制
std::hash<std::string>(largeString1) == std::hash<std::string>(largeString2)

会比

代码语言:javascript
复制
largeString1 == largeString2

对字符串进行散列处理涉及遍历整个字符串的长度。因此,哈希比较需要代码一次迭代两个字符串的全部长度,并通过复杂的方程运行它们。直接相等的代码只是在同一时间迭代它们,并在发现差异时立即退出。相信图书馆。如果==能做得更快,他们就会做得更快。

如果您要对每个字符串进行多次比较,那么先散列一次并比较散列可能会更快,但是您仍然需要确认匹配,因为比较散列可能会产生假阳性。它只会使“不匹配”的情况更快。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17887146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档