Introduction
Std::stringbuilder is based on Std::vector implementations. So although this article discusses std::vector, all the conclusions are equally valid for Std::stringbuilder.
Implementation overview
In simple terms, std::vector is a dynamic array that manages a linear, dynamically growing memory.
How to speed up std::vector?
Using Vector::reserve
When you approximate the vector size, you should first call the reserve (size) for pre-allocation of memory (size is the number of vector elements estimated) before inserting data.
Avoid inserting/deleting data at vector start (begin)
That is, you should try to add/Remove data using Vector::insert (end (), ...) or vector::p ush_back/pop_back. Instead of using Vector::insert (Begin (), ...) operation. Vector does not provide push_front operations for one reason: inserting/deleting data from the beginning of a vector is inefficient.
If you need a lot of insert data at the beginning of the container, you can choose std::d eque (The advantages of vector random access, the advantages of a list efficient insertion) or std::list.
Std::vector's flaws
When can you not use std::vector?
When the container needs to accommodate a large amount of data, and the number of elements unpredictable, we can not use std::vector. All data structures based on linear memory, such as std::vector,std::string, encounter performance bottlenecks when they are massive.
Memory fragmentation
Data structures based on linear memory (such as std::vector,std::string) also have a typical problem, which is that memory fragmentation is easy to produce. After a large number of operations std::vector or std::string, memory fragmentation is more serious.
Std::vector and Allocator
We know that the prototype of Std::vector is:
template <class DataT, class AllocT = std::allocator<DataT> >
class vector;
Is it necessary to use hashset/hashmultiset as we do for Map/multimap, Set/multiset, List/slist, Hashmap/hashmultimap, Deque, alloct What about GC allocator?
The answer is: no need. GC allocator is useful for improving small memory allocations. However, the dynamic linear memory data structure is invalid. This kind of data structure in addition to std::vector, typically there are std::string (std::basic_string).
Recommended Readings
std::d eque (Http://cpp.winxgui.com/cn:std-deque)-a data structure between std::vector and std::list that can be randomly positioned, and massive data is still very robust (in fact its The performance of Push_back/push_front is almost constant: O (1), rather than std::vector, the insertion rate drops dramatically as the element increases.
Std::list (http://cpp.winxgui.com/cn:std-list)-bidirectional linked list.