std :: string :: replace()是否针对相同长度的字符串进行了优化?

时间:2013-01-14 15:16:56

标签: c++ optimization replace stdstring

假设,大部分时间我都有以下方案进行替换:

std::string line; // "line" contains a big string.
std::string from = "abcd";
std::string to = "xy";  // to.length() < from.length()
// replace "from" with "to" everywhere in "line"

此处string类必须放"xy"然后删除2个字符,这有效地将line中的所有字符向左移动。在我的代码的整个生命周期中发生了很多这样的替换。

现在回答真正的问题。以下也适合我:

// ...
if(to.legnth() < from.length())
  to.resize(from.length(), ' ');
// now to.length() = from.length()
// replace "from" with "to" everywhere in "line"

仅当replace()针对相同长度的字符串进行了优化时,上述练习才有用。应该是因为那是微不足道的;但只是想确认某人是否拥有第一手知识 我尝试将Eclipse IDE浏览到字符串类中,但无法深入研究。

1 个答案:

答案 0 :(得分:4)

我只看一下MSVC 2008的实现。他们优化(我省略了一些东西):

_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
        }
        ...
    }

请注意,新长度较小的情况和长度相等的情况相似。

编辑:可以得出结论,在复制数据之后,在相同长度的字符串的情况下,必须移动/填充总“0”字符/孔(即,没有移动)。因此,实际上并不需要进行优化,但是它非常谨慎。