Is std::string::replace() optimized for same length strings?

大城市里の小女人 提交于 2019-12-05 23:27:49
borisbn

I just look at MSVC 2008's implementation. They do optimize (I omit some stuff):

_Myt& __CLR_OR_THIS_CALL replace(size_type _Off,
    size_type _N0, const _Myt& _Right, size_type _Roff, size_type _Count)
{
    ...
        if (_Count <= _N0)
        {   // hole doesn't get larger, just copy in substring
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
            _Myptr() + _Roff, _Count);  // fill hole
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
            _Myptr() + _Off + _N0, _Nm);    // move tail down
        }
    else if (_Roff <= _Off)
        {   // hole gets larger, substring begins before hole
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
            _Myptr() + _Off + _N0, _Nm);    // move tail down
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
            _Myptr() + _Roff, _Count);  // fill hole
        }
    else if (_Off + _N0 <= _Roff)
        {   // hole gets larger, substring begins after hole
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
            _Myptr() + _Off + _N0, _Nm);    // move tail down
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
            _Myptr() + (_Roff + _Count - _N0), _Count); // fill hole
        }
    else
        {   // hole gets larger, substring begins in hole
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off, _Myres - _Off,
            _Myptr() + _Roff, _N0); // fill old hole
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off + _Count, _Myres - _Off - _Count,
            _Myptr() + _Off + _N0, _Nm);    // move tail down
        _Traits_helper::move_s<_Traits>(_Myptr() + _Off + _N0, _Myres - _Off - _N0, _Myptr() + _Roff + _Count,
            _Count - _N0);  // fill rest of new hole
        }
        ...
    }

Take an attantion, that the case when new length is smaller and the case when lengths are equal are similar.

Edit: It can be concluded that in the case of same length strings after copying data, total "0" characters/holes have to be moved/filled (i.e. no movement). Thus no optimization is really needed, but it's taken care trivially.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!