Do anyone know if there is a STL interface compatible string class that allocates memory for small strings on the stack (up to a certain threshold) and the heap for larger strings ?
I'm looking to optimize a program and I'm using allot of small local strings that easily could fit on the stack, instead of being allocated on the heap.
In the case of strings being initialized via string literals (ie: "stack" ), it is allocated in a read-only portion of memory. The string itself should not be modified, as it will be stored in a read-only portion of memory. The pointer itself can be changed to point to a new location.
Stack space contains specific values that are short-lived whereas Heap space used by Java Runtime to allocate memory to objects and JRE classes. In Java, strings are stored in the heap area. Why Java strings stored in Heap, not in Stack? String Literal is created by using a double quote.
Inside every std::string is a dynamically allocated array of char .
While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.
You can provide a custom allocator for std::basic_string
(it is the third template argument). This answer explains how use that and links to an implementation of a stack-allocator that can be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With