击碎你的 rope 神话

· · 算法·理论

:::info[写在前面]{open} 很抱歉这篇文章的早期版本(错误分析复杂度是假的)对大家造成了误导,继“块状链表”之后又一次误导了大家,真的很抱歉。 :::

很多人知道一种所谓“可持久化数据结构杀手”的容器:__gnu_cxx::rope(以下省去命名空间),认为它是一种块状链表,操作是 O(\sqrt{n}) 级别的。

错!

根据官方文档,rope 是一种“平衡树状 / DAG 状结构”。

那么是否说明 rope 的单次操作时间复杂度可以达到神话般的 O(\log{n}),搏杀一众可持久化数据结构?

半错!

理论是理论,实际是实际。根据这篇文章的测速,rope 的实际运行时间慢得发指!

那么接下来我将分析 rope 到底为什么这么慢……

:::warning[观前提示]{open} 笔者使用 WSL2 Ubuntu,编译器版本信息如下:

g++ (Ubuntu 15.2.0-16ubuntu1) 15.2.0
Copyright (C) 2025 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
如果想要实际操作,需要找到 rope 和 ropeimpl.h 两个文件,应该在同一文件夹下,根据版本环境不同或许有差异。

「懒」平衡

ropeimpl.h 中第 484 行开始:

  // Assumes left and right are not 0.
  // Does not increment (nor decrement on exception) child reference counts.
  // Result has ref count 1.
  template <class _CharT, class _Alloc>
    typename rope<_CharT, _Alloc>::_RopeRep*
    rope<_CharT, _Alloc>::
    _S_tree_concat(_RopeRep* __left, _RopeRep* __right)
    {
      using std::size_t;
      _RopeConcatenation* __result = _S_new_RopeConcatenation(__left, __right,
                                  __left->
                                  _M_get_allocator());
      size_t __depth = __result->_M_depth;

      if (__depth > 20
      && (__result->_M_size < 1000
          || __depth > size_t(__detail::_S_max_rope_depth))) // <- 这坨判断!!!
    {
      _RopeRep* __balanced;

      __try
        {
          __balanced = _S_balance(__result); // <- 这里触发平衡!!!
          __result->_M_unref_nonnil();
        }
      __catch(...)
        {
          rope::_C_deallocate(__result,1);
          __throw_exception_again;
        }
      // In case of exception, we need to deallocate
      // otherwise dangling result node.  But caller
      // still owns its children.  Thus unref is
      // inappropriate.
      return __balanced;
    }
      else
    return __result;
    }

而根据 rope 第 79 行:

  namespace __detail
  {
    enum { _S_max_rope_depth = 45 }; // <- 最大深度为 45
    enum _Tag {_S_leaf, _S_concat, _S_substringfn, _S_function};
  } // namespace __detail

说明这颗树(姑且认为是树)只有在:

  1. 深度超过 20 且大小小于 1000;
  2. 或深度超过 45

时,才会触发平衡!

说明大尺寸 rope 在深度 21~45 之间完全不重整,平衡是假的。

关于为何 rope 极力避免重建平衡。

回到刚才的代码,我们可以看到一个 _S_balance 函数。

我们来看看这个函数做了什么。

ropeimpl.h 第 1202 行后,分为三个函数:

_S_balance 函数:

  template <class _CharT, class _Alloc>
    typename rope<_CharT, _Alloc>::_RopeRep*
    rope<_CharT, _Alloc>::
    _S_balance(_RopeRep* __r)
    {
      _RopeRep* __forest[int(__detail::_S_max_rope_depth) + 1];
      _RopeRep* __result = 0;
      int __i;
      // Invariant:
      // The concatenation of forest in descending order is equal to __r.
      // __forest[__i]._M_size >= _S_min_len[__i]
      // __forest[__i]._M_depth = __i
      // References from forest are included in refcount.

      for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
    __forest[__i] = 0;
      __try
    {
      _S_add_to_forest(__r, __forest);                      // <- 这里调用!!!
      for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
        if (0 != __forest[__i])
          {
#ifndef __GC
        _Self_destruct_ptr __old(__result);
#endif
        __result = _S_concat(__forest[__i], __result);
        __forest[__i]->_M_unref_nonnil();
#if !defined(__GC) && __cpp_exceptions

#include <bits/requires_hosted.h> // GNU extensions are currently omitted
        __forest[__i] = 0;
#endif
          }
    }
      __catch(...)
    {
      for(__i = 0; __i <= int(__detail::_S_max_rope_depth); __i++)
        _S_unref(__forest[__i]);
      __throw_exception_again;
    }

      if (__result->_M_depth > int(__detail::_S_max_rope_depth))
    std::__throw_length_error(__N("rope::_S_balance"));
      return(__result);
    }

_S_add_to_forest 函数:

  template <class _CharT, class _Alloc>
    void
    rope<_CharT, _Alloc>::
    _S_add_to_forest(_RopeRep* __r, _RopeRep** __forest)
    {
      if (__r->_M_is_balanced)
    {
      _S_add_leaf_to_forest(__r, __forest);
      return;
    }

      {
    _RopeConcatenation* __c = (_RopeConcatenation*)__r;

    _S_add_to_forest(__c->_M_left, __forest);            // <- 递归!!!
    _S_add_to_forest(__c->_M_right, __forest);           // <- 递归!!!
      }
    }

_S_add_leaf_to_forest 函数:

  template <class _CharT, class _Alloc>
    void
    rope<_CharT, _Alloc>::
    _S_add_leaf_to_forest(_RopeRep* __r, _RopeRep** __forest)
    {
      _RopeRep* __insertee;     // included in refcount
      _RopeRep* __too_tiny = 0;     // included in refcount
      int __i;              // forest[0..__i-1] is empty
      std::size_t __s = __r->_M_size;

      for (__i = 0; __s >= _S_min_len[__i+1]/* not this bucket */; ++__i) // <- 这里!!!
    {
      if (0 != __forest[__i])
        {
#ifndef __GC
          _Self_destruct_ptr __old(__too_tiny);
#endif
          __too_tiny = _S_concat_and_set_balanced(__forest[__i],
                              __too_tiny);
          __forest[__i]->_M_unref_nonnil();
          __forest[__i] = 0;
        }
    }
// 部分略去。。。
    }

写得真丑

_S_add_to_forest 递归

在 _S_add_to_forest 中,我们惊讶地发现,这个操作是把整个子树的非平衡部分跑一遍!

根据我的初步分析(如果有大神能证的话欢迎写续集)整个是 O(\log sz) 的(sz 是子树大小)。

_S_add_leaf_to_forest 二进制计数器

标记处。

这个操作对每片叶子(或者平衡子树,这个可能性不大)按大小找桶位 i,桶被占就 _S_concat_and_set_balanced 合并后进位到下一个桶。

这个函数长这样:

      static _RopeRep*
      _S_concat_and_set_balanced(_RopeRep* __left, _RopeRep* __right)
      {
    _RopeRep* __result = _S_concat(__left, __right);
    if (_S_is_balanced(__result))
      __result->_M_is_balanced = true;
    return __result;
      }

发现调用了 _S_concat。

而这个函数长这样:

  template <class _CharT, class _Alloc>
    typename rope<_CharT, _Alloc>::_RopeRep*
    rope<_CharT, _Alloc>::
    _S_concat(_RopeRep* __left, _RopeRep* __right)
    {
      using std::size_t;
      if (0 == __left)
    {
      _S_ref(__right);
      return __right;
    }
      if (0 == __right)
    {
      __left->_M_ref_nonnil();
      return __left;
    }
      if (__detail::_S_leaf == __right->_M_tag)
    {
      if (__detail::_S_leaf == __left->_M_tag)
        {
          if (__right->_M_size + __left->_M_size <= size_t(_S_copy_max))
        return _S_leaf_concat_char_iter((_RopeLeaf*)__left,
                        ((_RopeLeaf*)__right)->_M_data,
                        __right->_M_size);
        }
      else if (__detail::_S_concat == __left->_M_tag
           && __detail::_S_leaf == ((_RopeConcatenation*)
                           __left)->_M_right->_M_tag)
        {
          _RopeLeaf* __leftright =
        (_RopeLeaf*)(((_RopeConcatenation*)__left)->_M_right);
          if (__leftright->_M_size
          + __right->_M_size <= size_t(_S_copy_max))
        {
          _RopeRep* __leftleft = ((_RopeConcatenation*)__left)->_M_left;
          _RopeRep* __rest = _S_leaf_concat_char_iter(__leftright,
                                  ((_RopeLeaf*)
                                   __right)->
                                  _M_data,
                                  __right->_M_size);
          __leftleft->_M_ref_nonnil();
          __try
            { return(_S_tree_concat(__leftleft, __rest)); }     // <- 这个地方!!!
          __catch(...)
            {
              _S_unref(__leftleft);
              _S_unref(__rest);
              __throw_exception_again;
            }
        }
        }
    }
      __left->_M_ref_nonnil();
      __right->_M_ref_nonnil();
      __try
    { return(_S_tree_concat(__left, __right)); }     // <- 这个地方!!!
      __catch(...)
    {
      _S_unref(__left);
      _S_unref(__right);
      __throw_exception_again;
    }
    }

又调用了一个 _S_tree_concat!

这个地方和最开始引入的时候是一个东西,所以这个地方相当于递归调用平衡。

重新观察:

  // Assumes left and right are not 0.
  // Does not increment (nor decrement on exception) child reference counts.
  // Result has ref count 1.
  template <class _CharT, class _Alloc>
    typename rope<_CharT, _Alloc>::_RopeRep*
    rope<_CharT, _Alloc>::
    _S_tree_concat(_RopeRep* __left, _RopeRep* __right)
    {
      using std::size_t;
      _RopeConcatenation* __result = _S_new_RopeConcatenation(__left, __right,
                                  __left->
                                  _M_get_allocator()); // <- 这个
      size_t __depth = __result->_M_depth;

      if (__depth > 20
      && (__result->_M_size < 1000
          || __depth > size_t(__detail::_S_max_rope_depth)))
    {
      _RopeRep* __balanced;

      __try
        {
          __balanced = _S_balance(__result);
          __result->_M_unref_nonnil();
        }
      __catch(...)
        {
          rope::_C_deallocate(__result,1);
          __throw_exception_again;
        }
      // In case of exception, we need to deallocate
      // otherwise dangling result node.  But caller
      // still owns its children.  Thus unref is
      // inappropriate.
      return __balanced;
    }
      else
    return __result;
    }

好的这个地方有个 new 看起来就不正常是不是。。。

看看:

static _RopeConcatenation*
      _S_new_RopeConcatenation(_RopeRep* __left, _RopeRep* __right,
                   allocator_type& __a)
      {
    _RopeConcatenation* __space = typename _Base::_CAlloc(__a).allocate(1);
    return new(__space) _RopeConcatenation(__left, __right, __a);
      }

怎么新开了一个节点!!!

别笑,还有第三关

回到我们的_S_balance 函数:

  template <class _CharT, class _Alloc>
    typename rope<_CharT, _Alloc>::_RopeRep*
    rope<_CharT, _Alloc>::
    _S_balance(_RopeRep* __r)
    {
      _RopeRep* __forest[int(__detail::_S_max_rope_depth) + 1];
      _RopeRep* __result = 0;
      int __i;
      // Invariant:
      // The concatenation of forest in descending order is equal to __r.
      // __forest[__i]._M_size >= _S_min_len[__i]
      // __forest[__i]._M_depth = __i
      // References from forest are included in refcount.

      for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
    __forest[__i] = 0;
      __try
    {
      _S_add_to_forest(__r, __forest);
      for (__i = 0; __i <= int(__detail::_S_max_rope_depth); ++__i)
        if (0 != __forest[__i])
          {
#ifndef __GC
        _Self_destruct_ptr __old(__result);
#endif
        __result = _S_concat(__forest[__i], __result);          // 你好。
        __forest[__i]->_M_unref_nonnil();
#if !defined(__GC) && __cpp_exceptions

#include <bits/requires_hosted.h> // GNU extensions are currently omitted
        __forest[__i] = 0;
#endif
          }
    }
      __catch(...)
    {
      for(__i = 0; __i <= int(__detail::_S_max_rope_depth); __i++)
        _S_unref(__forest[__i]);
      __throw_exception_again;
    }

      if (__result->_M_depth > int(__detail::_S_max_rope_depth))
    std::__throw_length_error(__N("rope::_S_balance"));
      return(__result);
    }

我觉得我挺不好的。。。

把 46 个桶(这个是最大限制深度约定的)从低到高 _S_concat 回一棵树,同样是每次开一个新节点。

合起来:子树里有 k 个叶子 / 平衡子树,一次 _S_balance \to 访问全部 k 个单元 + 新建约 k−1 个 concat 节点 + 相应次数的 mutex 引用计数。根据我们暂且认为 k\approx\log n 的,我暂时还没有找到合适的证明方法。

为什么说它「触发就是灾难」

触发条件和树高强相关,那么当我们树大小越大,平衡后最大深度就越大,操作中更容易触发 balance,然后一次 O(\log sz)。也就是说随着我们树的大小增加,整棵树是以超预期的速度越来越慢越来越慢越来越慢越来越慢……

也就是为什么这篇文章的测速中大数据的劣势如此显著。

为什么重分配节点显得这么变态

:::info[AI 的解释] __GC 是「Boehm GC」的编译开关——rope 最初就是为带垃圾回收的环境设计的数据结构,你现在用的非 GC 版本其实是它的降级 fallback。

出处

SGI STL 的扩展,作者就是 Hans Boehm 本人(Boehm GC 的作者)。源头是他 1995 年的论文 "Ropes: an Alternative to Strings"(Boehm, Atkinson, Plass),概念更早来自 Xerox PARC 的 Cedar 系统。目标场景非常具体:

文本编辑器里的大文档缓冲。一份几十 MB 的文件,用户不停做插入、删除、剪切粘贴(= concat + substring),还要求随时能撤销(= 保留历史版本)。

对照源码你能看到这些设计痕迹:

为什么你拿到的版本慢

libstdc++ 里的 rope 没有定义 __GC(GNU 发行版不带 Boehm GC),于是全部走 #else 分支:手工引用计数 + 每节点两个互斥锁 + 显式 _M_free_tree。也就是说:

一句话:rope 是 GC 时代的编辑器字符串库,理论复杂度是真的,但常数前提(GC 分配器、懒加载、持久共享)在 OI 场景一个都不成立。

概括一下主旨就是,我们所用的 rope 其实是环境不完整的阉割版,完整版反复分配新节点释放老节点的常数是不存在的(全部交给环境处理),而且应用场景文本编辑器也说明了这个东西为什么能如此优秀地记录历史版本。\ 值得注意的是给出的源码里面大量出现了 __GC 宏,其实就是完整环境的宏。

一些补充

细心的读者可能发现了。

欸你一直在讲 concat 什么什么的,我 insert 之类的操作会调用吗?

会!

我们来看 insert 的部分。

    public:
      void
      insert(size_type __p, const rope& __r) // 第一个
      {
    _RopeRep* __result =
      replace(this->_M_tree_ptr, __p, __p, __r._M_tree_ptr);  // 这个 replace 函数调用了 _S_concat
    _S_unref(this->_M_tree_ptr);
    this->_M_tree_ptr = __result;
      }

      void
      insert(size_type __p, size_type __n, _CharT __c) // 第二个
      {
    rope<_CharT,_Alloc> __r(__n,__c);
    insert(__p, __r); // 这是什么呢?其实就是前一行开了一个新的节点后调用第一个 insert
      }

      void
      insert(size_type __p, const _CharT* __i, size_type __n) // 第三个
      {
    _Self_destruct_ptr __left(_S_substring(this->_M_tree_ptr, 0, __p));
    _Self_destruct_ptr __right(_S_substring(this->_M_tree_ptr,
                        __p, size()));
    _Self_destruct_ptr __left_result(_S_concat_char_iter(__left, __i, __n, // 没错这个函数又是会调用 _S_concat
                                 _M_get_allocator()));
    // _S_ destr_concat_char_iter should be safe here.
    // But as it stands it's probably not a win, since __left
    // is likely to have additional references.
    _RopeRep* __result = _S_concat(__left_result, __right); // 哦原来这边有
    _S_unref(this->_M_tree_ptr);
    this->_M_tree_ptr = __result;
      }

      void
      insert(size_type __p, const _CharT* __c_string) // 第四个
      { insert(__p, __c_string, _S_char_ptr_len(__c_string)); } // 计算一个不知道什么长度然后调用第三个 insert

      void
      insert(size_type __p, _CharT __c) // 第五个
      { insert(__p, &__c, 1); } // 直接调用第三个 insert,传进去一个字符的长度

      void
      insert(size_type __p) // 第六个
      {
    _CharT __c = _CharT();
    insert(__p, &__c, 1); // 没错还是调用第三个
      }

      void
      insert(size_type __p, const _CharT* __i, const _CharT* __j) // 第七个
      {
    rope __r(__i, __j);
    insert(__p, __r); // 调用第一个 insert
      }

      void
      insert(size_type __p, const const_iterator& __i,
         const const_iterator& __j) // 第八个
      {
    rope __r(__i, __j);
    insert(__p, __r); // 调用第一个 insert
      }

      void
      insert(size_type __p, const iterator& __i,
         const iterator& __j) // 第九个
      {
    rope __r(__i, __j);
    insert(__p, __r); // 还是调用第一个 insert
      }

所以 insert 操作不管传什么值,最后都会调用 _S_concat。

扒一扒别的函数都差不多。

至此,我宣布 rope 在 OI 场景下已死。

后记:给出题人卡 rope 的一些建议

  1. 你需要把数据范围开大(不要太小了,可以到原来的 5 倍左右,或者原来正解离时限很远很远,可以开更大);
  2. 你需要测试正解在这个数据范围下跑多久;
  3. 你需要把时限适当调高保证正解无需奇异卡常;
  4. 然后你就会发现 rope 被卡高兴了(以单次查询 \log^2 为例,5 倍开大整体时间达不到 5 倍,但是 rope 直接多出来 5 倍的点,期望树高高 2 层,调用 _S_balance 的概率大大提升,重分配内存次数大大提升,或许直接飞走了)。

:::info[AIGC 使用声明]{open} 除了明确声明 AI 的部分,纯人工。 :::