I use all over my code std::string objects, most of them stack allocated. I replaced default new/delete operators to check the average memory allocation size and I was surprised to see that most allocations come from std::string and, this is very important, they are between 12 and 32 bytes! To optimize this(large number of small strings allocated from the free storage) I came with a simple solution:
With this implementation I will add 64 bytes memory overhead to all my strings with length > 64 add also (64-lenth) overhead to strings shorter than 64 bytes, but I will prevent all the allocations for small strings.
Did you tried such approach? Is it resonable to add this memory overhead, most of the time on the stack to save allocation time/memory fragmentation?
Is this approach better than custom str::string allocators?
The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to directly print and read strings. You can see in the above program that string can also be read using a single scanf statement.
A string is generally considered as a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding. String may also denote more general arrays or other sequence (or list) data types and structures.
In C programming, a string is a one-dimensional array of characters that ends with the special character '\0'. Character arrays or strings are used to manipulate text, such as words or sentences.
C does not have a built-in string function. To work with strings, you have to use character arrays.
Is it reasonable? It depends. Unless you have found yourself actually running out of memory by using std::string
or identified a real (as opposed to perceived) performance problem with continued allocation and deallocation, you're wasting your time doing this.
Don't get me wrong, you can (and I have) made great gains over standard allocators by using extra information unavailable to them. But, unless there's a real problem to be fixed, you're better off using the standard method and devoting your time elsewhere.
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