很多人知道一种所谓“可持久化数据结构杀手”的容器:__gnu_cxx::rope(以下省去命名空间),认为它是一种块状链表,操作是 级别的。
错!
根据官方文档,rope 是一种“平衡树状 / DAG 状结构”。
那么是否说明 rope 的单次操作时间复杂度可以达到神话般的 ,搏杀一众可持久化数据结构?
错!
理论是理论,实际是实际。根据这篇文章的测速,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 行开始:
// 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说明这颗树(姑且认为是树)只有在:
- 深度超过 20 且大小小于 1000;
- 或深度超过 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 中,我们惊讶地发现,这个操作是把整个树跑一遍!!!
整个是 的!
具体来说,这里对对每个 concat 节点递归左右,直到叶子或标记为 balanced 的子树为止,这个剪枝在高频次的修改操作下聊胜于无。。。
_S_add_leaf_to_forest 二进制计数器
标记处。
这个操作对每片叶子(或者平衡子树,这个可能性不大)按大小找桶位 ,桶被占就 _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;
}UPD:笔者是奶龙,没发现这个地方其实和最开始引入的是一个东西,所以这个地方相当于递归调用开点再平衡。也很变态啊。
好的这个地方有个 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 回一棵树,同样是每次开一个新节点。
合起来:树里有 个叶子 / 平衡子树,一次 _S_balance 访问全部 个单元 新建约 个 concat 节点 相应次数的 mutex 引用计数,结构整棵重建,而叶子存储元素上限 _S_copy_max = 23,所以 , 时一次 balance 四万多次开点。
为什么说它「触发就是灾难」
触发条件和树高强相关,那么当我们树大小越大,平衡后最大深度就越大,操作中更容易触发 balance,然后一次 。也就是说随着我们树的大小增加,整棵树是以超预期的速度越来越慢越来越慢越来越慢越来越慢……
也就是为什么这篇文章的测速中大数据的劣势如此显著。
为什么 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 宏,其实就是完整环境的宏。
一些补充
细心的读者可能发现了。
欸你一直在讲
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 的其它雷点(但是我感觉以上部分已经足够判它死刑了)。或者拆别的平板电视(感觉没有威能拆掉 /ll)。
后记:给出题人卡 rope 的一些建议
- 你需要把数据范围开大(不要太小了,可以到原来的 倍左右,或者原来正解离时限很远很远,可以开更大);
- 你需要测试正解在这个数据范围下跑多久;
- 你需要把时限适当调高保证正解无需奇异卡常;
- 然后你就会发现
rope被卡高兴了(以单次查询 为例, 倍开大整体时间达不到 倍,但是rope直接多出来 倍的点,期望树高高 层,调用_S_balance的概率大大提升,重分配内存次数大大提升,直接飞走了)。
AIGC 使用声明
除了明确声明 AI 的部分,纯人工。