C++中hashmap的一些使用建议

前言

相信大部分C++开发都会在项目里直接使用std::unorderd_map,实现方便快捷且没有依赖,当后来发现性能不足时则会用一些开源的性能较好的hashmap去替换掉当前std::unordered_map来获得不错的提升,但也止步于此。而本文则是想分享一下使用开源的hashmap时候的一些常规选型思路和使用技巧。

hash冲突的解决方案

首先回顾一下hash冲突的解决方案有哪些。

Open addressing

open addressing是通过探测或者搜索数组的方法找到未使用的bucket来解决hash冲突的。

优点

*  当hash冲突很小的时候,只需要访问对应的bucket就能获得对应的pair<key, value>,不需要再查找额外的数据结构,性能较好。

缺点

*  对hash函数的要求比较高,否则当hash冲突很大的时,查找速度会很慢。

 Separate chaining

或者叫closed addressing,当发生hash冲突时需要通过额外的数据结构来处理,比如链表或者红黑树。

优点

* hash冲突处理简单,比如采用链表来解决hash冲突的话,添加节点的时候直接在链表后面添加即可。

* 对hash函数要求会低一点,即便冲突稍微大一点,也能把查找速度控制得比较好。

缺点

* 由于需要额外的数据结构处理,性能在一般情况下不如Open addressing。

STL采用的是Separate chaining的方案。使用链表挂在bucket上解决冲突,当链表超过一定长度时转换为红黑树。

Flat Or Node

一般的开源库都会提供两种memory layout,一种叫flat,另一种叫node。

Flat

flat实现是指存储pair<key, value>的时候是直接存到对应的节点上。

优点

* 对比node少一次寻址,对cache更加友好,查找速度会更高。

缺点

* 对象不稳定,rehash的时候对象地址会修改,如果对象是个大结构的话rehash时的开销会比node要大。

Node

node实现是指在节点上只存储pair<key, value>的地址。而pair<key, value>则存储在另一块内存上。

优点

* 对象稳定,rehash的时候对象地址不修改,且rehash的效率不会被结构体影响。

缺点

* 查找多一次寻址,对cache不友好,查找速度会比flat要慢。

 

STL用的是Node的实现。每个pair<key, value>都是stable的。

使用建议

在hash冲突上,大部分的开源实现都选择了Open addressing这种方式,毕竟理论性能会更好,而flat和node则是两种实现都会提供。结合上面说的各种优缺点,我们可以简单得出一套通用的方案。

首先考虑下面几个点:

1. 是否可以一开始就可以确定好容量。

2. key的copy开销是否很大。

3. value的copy开销是否很大。

4. value的地址不稳定是否会影响代码逻辑。

可以简单归纳为以下四种情况:

情况1:value可以是不稳定的,而且容量是已知的,可以一开始确定。

推荐:使用flat实现,通过一开始reserve两倍的size来减少rehash带来的开销。

情况2:value可以是不稳定的,容量未知,key和value的copy开销很小。

推荐:使用flat实现。

情况3:value可以是不稳定的,容量未知,key的copy开销很小但value的copy开销很大。

推荐:使用flat实现,value使用unique_ptr包裹起来。

其他情况均使用node结构。

RobinHood

上面提到的规则基本可以适用大部分情况,但也不是没有例外,比如笔者在用这套规则去测试robinhood的性能的时候发现行不通,robinhood在绝大部分情况下都是node的实现性能会更高,除非value是个十分简单的结构。通过分析发现,这主要是因为以下两个原因:

1.robinhood在emplace的时候会有移动pair<key, value>的操作,这使得如果pair<key, value>的copy代价很高,性能会大打折扣。

2.robinhood实现了自己的allocator来分配node的内存,使得调用malloc的次数大约为log(n)次,并且内存连续的情况会变多,对CPU Cache比一般的node实现要友好。

具体我们可以看看源代码,首先是emplace的实现。

  1.      void nextWhileLess(InfoType* info, size_t* idx) const noexcept {
  2.          // unrolling this by hand did not bring any speedups.
  3.          while (*info < mInfo[*idx]) {
  4.              next(info, idx);
  5.          }
  6.      }
  7.      // Finds key, and if not already present prepares a spot where to pot the key & value.
  8.      // This potentially shifts nodes out of the way, updates mInfo and number of inserted
  9.      // elements, so the only operation left to do is create/assign a new node at that spot.
  10.      template <typename OtherKey>
  11.      std::pair<size_t, InsertionState> insertKeyPrepareEmptySpot(OtherKey&& key) {
  12.          for (int i = 0; i < 256; ++i) {
  13.              size_t idx{};
  14.              InfoType info{};
  15.              // 找到对应key的info
  16.              keyToIdx(key, &idx, &info);
  17.              // 跳过distance大于自己的
  18.              nextWhileLess(&info, &idx);
  19.              // while we potentially have a match
  20.              while (info == mInfo[idx]) {
  21.                  // distance相等的情况需要判key是不是已经存在了
  22.                  if (WKeyEqual::operator()(key, mKeyVals[idx].getFirst())) {
  23.                      // key already exists, do NOT insert.
  24.                      // see http://en.cppreference.com/w/cpp/container/unordered_map/insert
  25.                      return std::make_pair(idx, InsertionState::key_found);
  26.                  }
  27.                  next(&info, &idx);
  28.              }
  29.              // unlikely that this evaLuates to true
  30.              if (ROBIN_HOOD_UNLIKELY(mNumElements >= mMaxNumElementsAllowed)) {
  31.                  if (!increase_size()) {
  32.                      return std::make_pair(size_t(0), InsertionState::overflow_error);
  33.                  }
  34.                  continue;
  35.              }
  36.              // key not found, so we are now exactly where we want to insert it.
  37.              // 此时的位置原来的distance一定是小于当前的distance
  38.              auto const insertion_idx = idx;
  39.              auto const insertion_info = info;
  40.              if (ROBIN_HOOD_UNLIKELY(insertion_info + mInfoInc > 0xFF)) {
  41.                  mMaxNumElementsAllowed = 0;
  42.              }
  43.              // find an empty spot
  44.              // 找到下一个空白的位置
  45.              while (0 != mInfo[idx]) {
  46.                  next(&info, &idx);
  47.              }
  48.              // 如果当前的位置不是空白的,则把当前位置->下一个空白位置的所有元素往后移
  49.              if (idx != insertion_idx) {
  50.                  shiftUp(idx, insertion_idx);
  51.              }
  52.              // put at empty spot
  53.              mInfo[insertion_idx] = static_cast<uint8_t>(insertion_info);
  54.              ++mNumElements;
  55.              return std::make_pair(insertion_idx, idx == insertion_idx
  56.                      ? InsertionState::new_node
  57.                      : InsertionState::overwrite_node);
  58.          }
  59.          // enough attempts failed, so finally give up.
  60.          return std::make_pair(size_t(0), InsertionState::overflow_error);
  61.      }
  62.      template <typename OtherKey, typename Args>
  63.      std::pair<iterator, bool> try_emplace_impl(OtherKey&& key, Args&&… args) {
  64.          ROBIN_HOOD_TRACE(this)
  65.          auto idxAndState = insertKeyPrepareEmptySpot(key);
  66.          switch (idxAndState.second) {
  67.          case InsertionState::key_found:
  68.              break;
  69.          case InsertionState::new_node:
  70.              ::new (static_cast<void*>(&mKeyVals[idxAndState.first])) Node(
  71.                  *this, std::piecewise_construct, std::forward_as_tuple(std::forward<OtherKey>(key)),
  72.                  std::forward_as_tuple(std::forward<Args>(args)…));
  73.              break;
  74.          case InsertionState::overwrite_node:
  75.              mKeyVals[idxAndState.first] = Node(*this, std::piecewise_construct,
  76.                      std::forward_as_tuple(std::forward<OtherKey>(key)),
  77.                      std::forward_as_tuple(std::forward<Args>(args)…));
  78.              break;
  79.          case InsertionState::overflow_error:
  80.              throwOverflowError();
  81.              break;
  82.          }
  83.          return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),
  84.                      InsertionState::key_found != idxAndState.second);
  85.      }

这里robinhood有一个很神奇的操作,它在info里面存了一个distance,这个distance表示当前元素所在位置与初始位置的距离,简单举例,假设我插入了4个key,分别为a,b,c,d。

-1

sequence1:插入a,hash(a) == 0,此时index0是空的,直接插入。它的distance(0, 0) == 0。

sequence2:插入b,hash(b) == 1,此时index1是空的,直接插入。它的distance(1, 1) == 0。

sequence3:插入c,hash(c) == 1,此时index1存在,那么找到下一个位置2插入,它的distance(1, 2) == 1。

sequence4:插入d,hash(d) == 1,此时index1和2都存在,找到位置3插入,它的distance(1, 3) == 2。

至于它的移动操作是怎么来的呢,假设基于上面的流程此时再加一个插入元素e的操作,并且这时候hash(e) == 0,首先是index0,发现这个位置两者的distance是相同,所以跳过看下一个。而index1则满足条件(新的距离>当前b这个key的距离),所以会把e放到index1这个位置,并且找到下一个空白的位置index4,然后把c, d这两个元素后移,最终会变成下面这个图。

-2

分配内存这块就比较简单了。

  1.      T* allocate() {
  2.          T* tmp = mHead;
  3.          if (!tmp) {
  4.              tmp = performAllocation();
  5.          }
  6.          mHead = *reinterpret_cast_no_cast_align_warning<T**>(tmp);
  7.          return tmp; }
  8.      ROBIN_HOOD(NOINLINE) T* performAllocation() {
  9.          size_t const numElementsToAlloc = calcNumElementsToAlloc();
  10.          // alloc new memory: [prev |T, T, … T]
  11.          size_t const bytes = ALIGNMENT + ALIGNED_SIZE * numElementsToAlloc;
  12.          ROBIN_HOOD_LOG(“std::malloc “ << bytes << ” = “ << ALIGNMENT << ” + “ << ALIGNED_SIZE
  13.                      << ” * “ << numElementsToAlloc)
  14.          add(assertNotNull<std::bad_alloc>(std::malloc(bytes)), bytes);
  15.          return mHead;
  16.      }
  17.      ROBIN_HOOD(NODISCARD) size_t calcNumElementsToAlloc() const noexcept {
  18.          auto tmp = mListForFree;
  19.          size_t numAllocs = MinNumAllocs;
  20.          while (numAllocs * 2 <= MaxNumAllocs && tmp) {
  21.              auto x = reinterpret_cast<T***>(tmp);
  22.              tmp = *x;
  23.              numAllocs *= 2;
  24.          }
  25.          return numAllocs;
  26.      }

每次都分配比原来更多的内存,所以大概是分配log(n)次。

所以如果是用的robinhood,笔者建议除非你的pair<key, value>真的是非常简单的结构,否则都是用node实现会好一点。或者你可以交给robinhood自己判断,不显示指定使用flat还是node,robinhood的模板会自动根据你的size去判断去使用哪个实现。

  1. using unordered_map =
  2.      detail::Table<sizeof(robin_hood::pair<Key, T>) <= sizeof(size_t) * 6 &&
  3.                      std::is_nothrow_move_constructible<robin_hood::pair<Key, T>>::value &&
  4.                      std::is_nothrow_move_assignable<robin_hood::pair<Key, T>>::value,
  5.                      MaxLoadFactor100, Key, T, Hash, KeyEqual>;
  6. template <bool IsFlat, size_t MaxLoadFactor100, typename Key, typename T, typename Hash,
  7.              typename KeyEqual>
  8. class Table
  9.      : public WrapHash<Hash>,
  10.          public WrapKeyEqual<KeyEqual>,
  11.          detail::NodeAllocator<
  12.              typename std::conditional<
  13.                  std::is_void<T>::value, Key,
  14.                  robin_hood::pair<typename std::conditional<IsFlat, Key, Key const>::type, T>>::type,
  15.              4, 16384, IsFlat> {}

RobinHood VS Absl

这里附带上一个简单的benchmark测试robinhood和absl的性能,测试的key是uint32_t类型,value是个120size的结构。测试代码如下

  1. //
  2. // Created by victorika on 2022/10/14.
  3. //
  4. #include “absl/container/flat_hash_map.h”
  5. #include “absl/container/node_hash_map.h”
  6. #include <vector>
  7. #include <cstdio>
  8. #include <IOStream>
  9. #define ANKERL_NANOBENCH_IMPLEMENT
  10. #include “riemann/3rd/nanobench/nanobench.h”
  11. #include “robin_hood.h”
  12. /**
  13.      * 测试结构
  14.      */
  15. struct TestStruct {
  16.      uint32_t* a;
  17.      std::vector<uint32_t> b, c, d;
  18.      std::string e, f, g;
  19.      uint32_t h, i, j;
  20. };
  21. void TestEmplace() {
  22.      ankerl::nanobench::Bench bench;
  23.      bench.minEpochIterations(50);
  24.      bench.title(“Benchmarking rare value emplace”);
  25.      bench.run(“absl_flat”, [&] {
  26.      absl::flat_hash_map<uint32_t, TestStruct> m;
  27.      for (int i = 0; i < 10000; i++) {
  28.          m.try_emplace(i, TestStruct());
  29.      }
  30.      });
  31.      bench.run(“absl_flat_and_set_value_pointer”, [&] {
  32.      absl::flat_hash_map<uint32_t, std::unique_ptr<TestStruct>> m;
  33.      for (int i = 0; i < 10000; i++) {
  34.          m.try_emplace(i, std::make_unique<TestStruct>());
  35.      }
  36.      });
  37.      bench.run(“absl_node”, [&] {
  38.      absl::node_hash_map<uint32_t, TestStruct> m;
  39.      for (int i = 0; i < 10000; i++) {
  40.          m.try_emplace(i, TestStruct());
  41.      }
  42.      });
  43.      bench.run(“absl_flat_reserve”, [&] {
  44.      absl::flat_hash_map<uint32_t, TestStruct> m;
  45.      m.reserve(20000);
  46.      for (int i = 0; i < 10000; i++) {
  47.          m.try_emplace(i, TestStruct());
  48.      }
  49.      });
  50.      bench.run(“absl_flat_and_set_value_pointer_reserve”, [&] {
  51.      absl::flat_hash_map<uint32_t, std::unique_ptr<TestStruct>> m;
  52.      m.reserve(20000);
  53.      for (int i = 0; i < 10000; i++) {
  54.          m.try_emplace(i, std::make_unique<TestStruct>());
  55.      }
  56.      });
  57.      bench.run(“absl_node_reserve”, [&] {
  58.      absl::node_hash_map<uint32_t, TestStruct> m;
  59.      m.reserve(20000);
  60.      for (int i = 0; i < 10000; i++) {
  61.          m.try_emplace(i, TestStruct());
  62.      }
  63.      });
  64.      bench.run(“robinhood_flat”, [&] {
  65.      robin_hood::unordered_flat_map<uint32_t, TestStruct> m;
  66.      for (int i = 0; i < 10000; i++) {
  67.          m.try_emplace(i, TestStruct());
  68.      }
  69.      });
  70.      bench.run(“robinhood_flat_and_set_value_pointer”, [&] {
  71.      robin_hood::unordered_flat_map<uint32_t, std::unique_ptr<TestStruct>> m;
  72.      for (int i = 0; i < 10000; i++) {
  73.          m.try_emplace(i, std::make_unique<TestStruct>());
  74.      }
  75.      });
  76.      bench.run(“robinhood_node”, [&] {
  77.      robin_hood::unordered_node_map<uint32_t, TestStruct> m;
  78.      for (int i = 0; i < 10000; i++) {
  79.          m.try_emplace(i, TestStruct());
  80.      }
  81.      });
  82.      bench.run(“robinhood_flat_reserve”, [&] {
  83.      robin_hood::unordered_flat_map<uint32_t, TestStruct> m;
  84.      m.reserve(20000);
  85.      for (int i = 0; i < 10000; i++) {
  86.          m.try_emplace(i, TestStruct());
  87.      }
  88.      });
  89.      bench.run(“robinhood_flat_and_set_value_pointer_reserve”, [&] {
  90.      robin_hood::unordered_flat_map<uint32_t, std::unique_ptr<TestStruct>> m;
  91.      m.reserve(20000);
  92.      for (int i = 0; i < 10000; i++) {
  93.          m.try_emplace(i, std::make_unique<TestStruct>());
  94.      }
  95.      });
  96.      bench.run(“robinhood_node_reserve”, [&] {
  97.      robin_hood::unordered_node_map<uint32_t, TestStruct> m;
  98.      m.reserve(20000);
  99.      for (int i = 0; i < 10000; i++) {
  100.          m.try_emplace(i, TestStruct());
  101.      }
  102.      });
  103. }
  104. void TestSearch() {
  105.      absl::flat_hash_map<uint32_t, TestStruct> m1;
  106.      absl::flat_hash_map<uint32_t, std::unique_ptr<TestStruct>> m2;
  107.      absl::node_hash_map<uint32_t, TestStruct> m3;
  108.      robin_hood::unordered_flat_map<uint32_t, TestStruct> m4;
  109.      robin_hood::unordered_flat_map<uint32_t, std::unique_ptr<TestStruct>> m5;
  110.      robin_hood::unordered_node_map<uint32_t, TestStruct> m6;
  111.      for (int i = 0; i < 10000; i++) {
  112.      m1.try_emplace(i, TestStruct());
  113.      m2.try_emplace(i, std::make_unique<TestStruct>());
  114.      m3.try_emplace(i, TestStruct());
  115.      m4.try_emplace(i, TestStruct());
  116.      m5.try_emplace(i, std::make_unique<TestStruct>());
  117.      m6.try_emplace(i, TestStruct());
  118.      }
  119.      ankerl::nanobench::Bench bench;
  120.      bench.minEpochIterations(50);
  121.      std::vector<uint32_t> key_v;
  122.      key_v.resize(10000);
  123.      bench.title(“Benchmarking rare value search”);
  124.      bench.run(“absl_flat_normal”, [&] {
  125.      for (int i = 0; i < 10000; i++) {
  126.          auto it = m1.find(i);
  127.          key_v[i] = it->first;
  128.      }
  129.      });
  130.      bench.run(“absl_flat_unique_ptr”, [&] {
  131.      for (int i = 0; i < 10000; i++) {
  132.          auto it = m2.find(i);
  133.          key_v[i] = it->first;
  134.      }
  135.      });
  136.      bench.run(“absl_node”, [&] {
  137.      for (int i = 0; i < 10000; i++) {
  138.          auto it = m3.find(i);
  139.          key_v[i] = it->first;
  140.      }
  141.      });
  142.      bench.run(“robinhood_flat_normal”, [&] {
  143.      for (int i = 0; i < 10000; i++) {
  144.          auto it = m4.find(i);
  145.          key_v[i] = it->first;
  146.      }
  147.      });
  148.      bench.run(“robinhood_unique_ptr”, [&] {
  149.      for (int i = 0; i < 10000; i++) {
  150.          auto it = m5.find(i);
  151.          key_v[i] = it->first;
  152.      }
  153.      });
  154.      bench.run(“robinhood_node”, [&] {
  155.      for (int i = 0; i < 10000; i++) {
  156.          auto it = m6.find(i);
  157.          key_v[i] = it->first;
  158.      }
  159.      });
  160. }
  161. void TestIterator() {
  162.      absl::flat_hash_map<uint32_t, TestStruct> m1;
  163.      absl::flat_hash_map<uint32_t, std::unique_ptr<TestStruct>> m2;
  164.      absl::node_hash_map<uint32_t, TestStruct> m3;
  165.      robin_hood::unordered_flat_map<uint32_t, TestStruct> m4;
  166.      robin_hood::unordered_flat_map<uint32_t, std::unique_ptr<TestStruct>> m5;
  167.      robin_hood::unordered_node_map<uint32_t, TestStruct> m6;
  168.      for (int i = 0; i < 10000; i++) {
  169.      m1.try_emplace(i, TestStruct());
  170.      m2.try_emplace(i, std::make_unique<TestStruct>());
  171.      m3.try_emplace(i, TestStruct());
  172.      m4.try_emplace(i, TestStruct());
  173.      m5.try_emplace(i, std::make_unique<TestStruct>());
  174.      m6.try_emplace(i, TestStruct());
  175.      }
  176.      ankerl::nanobench::Bench bench;
  177.      bench.minEpochIterations(50);
  178.      std::vector<uint32_t> key_v;
  179.      key_v.resize(10000);
  180.      bench.title(“Benchmarking rare value iterator”);
  181.      bench.run(“absl_flat_normal”, [&] {
  182.      int i = 0;
  183.      for (auto &[key, value] : m1) {
  184.          key_v[i] = key;
  185.      }
  186.      });
  187.      bench.run(“absl_flat_unique_ptr”, [&] {
  188.      int i = 0;
  189.      for (auto &[key, value] : m2) {
  190.          key_v[i] = key;
  191.      }
  192.      });
  193.      bench.run(“absl_node”, [&]() {
  194.      int i = 0;
  195.      for (auto &[key, value] : m3) {
  196.          key_v[i] = key;
  197.      }
  198.      });
  199.      bench.run(“robinhood_flat_normal”, [&] {
  200.      for (int i = 0; i < 10000; i++) {
  201.          auto it = m4.find(i);
  202.          key_v[i] = it->first;
  203.      }
  204.      });
  205.      bench.run(“robinhood_flat_unique_ptr”, [&] {
  206.      for (int i = 0; i < 10000; i++) {
  207.          auto it = m5.find(i);
  208.          key_v[i] = it->first;
  209.      }
  210.      });
  211.      bench.run(“robinhood_node”, [&] {
  212.      for (int i = 0; i < 10000; i++) {
  213.          auto it = m6.find(i);
  214.          key_v[i] = it->first;
  215.      }
  216.      });
  217. }
  218. int main() {
  219.      std::cout << “size=” << sizeof(TestStruct) << std::endl;
  220.      TestEmplace();
  221.      TestSearch();
  222.      TestIterator();
  223. }

测试结果

-3

可以看到,在value copy rare的场景,absl的性能完全遵循上面提到的规则,而robinhood在这种情况下,emplace+construct+deconstruct是node更快,查找和遍历几乎和flat没区别。横向对比absl和robinhood两者的话,在查找和遍历上都是absl更快,emplace+construct+deconstruct在优化到极致的情况下两者差不多,robinhood并没有比absl快多少。当然,这只是简单测试,针对key类型不同的场景可能两者速度不太一样,具体就需要更加详细的benchmark了。

笔者也尝试过极简类型的场景,结论也没有违背上面的规则,都是flat速度远大于node。

建议:从两者里面选择的话,如果选型是用flat的话建议用absl,是node的话建议用robinhood

总结

到此这篇关于C++中hashmap的一些使用建议的文章就介绍到这了,更多相关C++ hashmap使用建议内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论