<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/61013>61013</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
std::string unnecessarily maintains a null terminated char array all the time.
</td>
</tr>
<tr>
<th>Labels</th>
<td>
libc++,
performance
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
hiraditya
</td>
</tr>
</table>
<pre>
This is probably out of convenience to simplify `data()` or `c_str()`. There is no need to maintain a null terminated char-array inside std::string. Because of this all the operations that increase the size of string has a redundant operation that adds a null-byte at the end of the string.
e.g., insert, push_back
```cpp
basic_string<_CharT, _Traits, _Allocator>::insert(const_iterator __pos, value_type __c)
{
...
traits_type::assign(__p[__ip], __c);
traits_type::assign(__p[++__sz], value_type()); // extra assignment
```
for push_back
```cpp
void
basic_string<_CharT, _Traits, _Allocator>::push_back(value_type __c)
{
...
traits_type::assign(*__p, __c);
traits_type::assign(*++__p, value_type()); // extra assignment
```
This extra assignment hurts performance. For example `std::getline` calls `string::push_back` for each character [https://github.com/llvm/llvm-project/issues/21566]
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyslNGOqzYQhp_G3IwWgQmEXHCR7DZPsPdosCfBrbGRPaxOztNXhuxmu0dV1XYllFjG88_vz_jHGM3VEXWiPon6JcOFRx-60QTUhm-YDV7futfRRDAR5uAHHOwN_MLgL6C8eyNnyCkC9hDNNFtzuYFoCo2MQrZCHkRTgA9pTvWRw8dkDq8jBUq6zoMj0kljQuMYjQMEt1gLTGEyDpk0qBHDE4aANzAuGk0QWYvqKKpj5GDcNYcTKVwiJW-cPGNSGAn8TAHZeBeBR2QwTgXCSOvLaH6uFZsIjBgBIZBenEbHj9qtFLWOd3NPw40JkFcVcnprS3ehXBQvojhuv5RfcyGfk3EKnEbzEsd-QPXH52WiKbZHzfM2M2A0KzfjrqJ67p9HDK-pvn8NaDiuw6O1XiH7IKrfNiDvfVrlXeTecNqDD9D3s19r3tAu1PNtJuh7lU5kM7A_bYM8v_sHXvusSzft7ZsRsu37WdSnvjezqF9WI5tSddcAgH-sFjI9fR9_3jUexu5fyioIQp6FPAP94ICwaUzk-Au2zywvPvwC-Re8b97o_wX60UG238FUyGMC829hCnl8Jzl_K8X16n9dD-MSOMJM4eLDhE5RDmcfgH7gNFtKd_3jal6JrXGUUkChtXF7uVH-K8CmgHRmhGpc7zoqpgCiPo3Mc0yrV_dXw-My5MpPQp6tfXv_e5qD_50UC3k2MS4UhTzLsm6alGu6q_ShOmBGXdns97umOBRVNnaSSEmly-GwV7i_lEWjm3ZXq4tu26Gs2sx0spBVIeW-KGW5k3lTX9T-gjjIVtW6VGJX0ITG5slD7sM1W7t3TVmUVWZxIBvXdJXSmkFtpySkFPJZSPkJYZqrX7LQrZsZlmsUu8KayPEhzYYtdV9iDxbnSFGMGIy9fSRo_JsIhS1C36ORzUR5tgTb_XfM617_DAAA__9Be_07">