Closed jingkaimori closed 7 months ago
reserve
std::basic_string::reserve
a_N
std::basic_string::capacity
expand_or_shrink_by
resize
std::basic_string::resize
std::basic_string::shrink_to_fit
use reserve() along with append operator:
reserve()
string r; r.reserve(100); for(int i=0; i<100; i++){ r << (i%26) + 'a'; }
construct string
append string
Could you explain why we need to add two extra interfaces? Are there similar designs in other C++ string libraries?
Works
reserve
method;std::basic_string::reserve
a_N
field;std::basic_string::capacity
expand_or_shrink_by
method to accelerate append of string.expand_or_shrink_by
avoid re-allocation whenever possible, so if a large string is shrink byexpand_or_shrink_by
, memory is not released.resize
works likestd::basic_string::resize
, sometimesresize
can be used asstd::basic_string::shrink_to_fit
.Example
use
reserve()
along with append operator:Performance
Before
construct string
append string
After
construct string
append string