boostorg / container

STL-like containers from Boost
http://www.boost.org/libs/container/
Boost Software License 1.0
96 stars 116 forks source link

`basic_string::clear()` has poor codegen compared to STL implementations #192

Closed cmazakas closed 2 years ago

cmazakas commented 2 years ago

Consider the following snippets of code: https://godbolt.org/z/nEdj6hzoa

Boost.Container's implementation seems to generate poor instructions in comparison to libstdc++.

pdimov commented 2 years ago

The current implementation of clear() https://github.com/boostorg/container/blob/bfbab6ed7f641f62ba53093a9ae205970039e2b4/include/boost/container/string.hpp#L1951-L1962 computes unnecessarily the size in empty() and repeatedly checks is_short() because of (I assume) aliasing issues when storing chars.

Doing the is_short check once, and eliminating the empty check, in effect doing something like if( is_short() ) priv_short_clear(); else priv_long_clear(); gives a much better codegen: https://godbolt.org/z/s1WG7rMr3 (gcc) https://godbolt.org/z/6nKrvWT1r (clang).

igaztanaga commented 2 years ago

Many thanks for the report and many thanks Peter for the fix, I'll apply it as suggested. Reviewing other implementations, they also check is_short() and perform specialised steps in each case.