Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String class allocating on stack for small strings?

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.

like image 870
ROAR Avatar asked Mar 24 '11 12:03

ROAR


People also ask

Are strings allocated on the stack?

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.

Are strings allocated on heap or stack?

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.

Is std::string dynamically allocated?

Inside every std::string is a dynamically allocated array of char .

Does std::string allocate?

While std::string has the size of 24 bytes, it allows strings up to 22 bytes(!!) with no allocation.


1 Answers

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.

like image 88
Björn Pollex Avatar answered Sep 22 '22 06:09

Björn Pollex