跳到正文

算法·理论

击碎你的 rope 神话

albertting约 22 分钟
原文

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

文章信息与版本

文章信息

发布
2026年8月23日
收录
2026年8月23日
更新
2026年11月22日
篇幅
约 22 分钟
获赞
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 已死。

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

AIGC 使用声明

纯人工。