跳到正文

算法·理论

击碎你的 rope 神话

albertting约 25 分钟
原文

这是 2026年8月24日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年8月23日
收录
2026年8月23日
更新
2026年11月22日
篇幅
约 25 分钟
获赞
3

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1

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

错!

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

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

错!

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

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

观前提示

笔者使用 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 行开始:

C++
  // 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 行:

C++
  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 函数:

C++
  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 函数:

C++
  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 函数:

C++
  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(size)O(size) 的!

具体来说,这里对对每个 concat 节点递归左右,直到叶子或标记为 balanced 的子树为止,这个剪枝在高频次的修改操作下聊胜于无。。。

_S_add_leaf_to_forest 二进制计数器

标记处。

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

这个函数长这样:

C++
      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。

而这个函数长这样:

C++
  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!

没完没了了

这个东西是什么呢:

C++
  // 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 看起来就不正常是不是。。。

看看:

C++
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);
      }

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

回到开始,如果有 kk 片叶子进森林,进位合并总次数 ≈k\approx k(每次合并少一棵树),也就是 kk 次新节点分配。

这个复杂度不是爆了吗。。。

别笑,还有第三关

回到我们的_S_balance 函数:

C++
  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 回一棵树,同样是每次开一个新节点。

合起来:树里有 kk 个叶子 / 平衡子树,一次 _S_balance →\to 访问全部 kk 个单元 ++ 新建约 k−1k−1 个 concat 节点 ++ 相应次数的 mutex 引用计数,结构整棵重建,而叶子上限 _S_copy_max = 23,所以 k≈n23k\approx \frac{n}{23},n=106n=10^6 时一次 balance ≈\approx 四万多次开点。

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

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

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

为什么 rope 显得这么变态

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),还要求随时能撤销(= 保留历史版本)。

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

  • 持久共享:rope 是不可变的,concat/substr 产生的新 rope 与旧的共享子树(引用计数/__GC 下靠 GC),天然支持「保留旧版本」——撤销功能零成本;
  • 懒加载文件:头文件 149~152 行注释明说了——char_producer 让 “files can be viewed as ropes without reading the entire file”。打开大文件先建个 _RopeFunction 节点,读到哪段才真正读盘,这就是源码里 _S_function / _S_substringfn 这类节点的存在理由(也是你随机访问会撞上「每字符一次虚函数调用」的根源);
  • GC 优先的内存模型:#ifdef __GC 分支里 _M_incr/_M_decr/_S_ref/_S_unref 全是空函数(头文件 695~701 行),_S_free_string 也什么都不做(ropeimpl.h 414 行)——内存全交给 Boehm conservative collector 扫,连 _RopeFunction 里的 char_producer 都是用 GC_REGISTER_FINALIZER(头文件 847 行)注册的析构回调。在 GC 环境下,concat 就是「分配一个节点、写两个指针」,没有任何记账开销,malloc 走 GC 的 allocator 也很快。

为什么你拿到的版本慢

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

  • 原作者眼里的常数大头(GC 分配 + 无 refcount)在你这里根本不存在;
  • 你跑的是「给没有 GC 的用户凑合用」的兼容路径,refcount 的锁、逐节点 malloc/free 全是后补的开销;
  • 它优化的是「10⁷~10⁸ 字符、操作次数不多」的编辑器负载,不是 OI 的「10⁵ 次操作、1 秒时限」。

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

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


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

如果呼声高,考虑加更 rope 的其它雷点(但是我感觉以上部分已经足够判它死刑了)。或者拆别的平板电视(感觉没有威能拆掉 /ll)。

AIGC 使用声明

除了明确声明 AI 的部分,纯人工。