Victor Parmar
Victor Parmar

Reputation: 5779

C++ string literals vs. const strings

I know that string literals in C/C++ have static storage duration, meaning that they live "forever", i.e. as long as the program runs.

Thus, if I have a function that is being called very frequently and uses a string literal like so:

void foo(int val)
{
    std::stringstream s;
    s << val;
    lbl->set_label("Value: " + s.str());
}

where the set_label function takes a const std::string& as a parameter.

Should I be using a const std::string here instead of the string literal or would it make no difference?

I need to minimise as much runtime memory consumption as possible.

edit:

I meant to compare the string literal with a const std::string prefix("Value: "); that is initialized in some sort of a constants header file.

Also, the concatenation here returns a temporary (let us call it Value: 42 and a const reference to this temporary is being passed to the function set_text(), am I correct in this?

Thank you again!

Upvotes: 7

Views: 6555

Answers (4)

Ben Voigt
Ben Voigt

Reputation: 283624

This will use less memory and run much faster (use snprintf if your compiler supports it):

void foo(int val)
{
    char msg[32];
    lbl->set_label(std::string(msg, sprintf(msg, "Value: %d", val)));
}

For even faster implementations, check out C++ performance challenge: integer to std::string conversion

Upvotes: 2

engf-010
engf-010

Reputation: 3929

Store them in some kind of resource and load/unload them as necessary.

Upvotes: 0

kriss
kriss

Reputation: 24177

How will you build your const std::string ? If you do it from some string literral, in the end it will just be worse (or identical if compiler does a good job). A string literal does not consumes much memory, and also static memory, that may not be the kind of memory you are low of.

If you can read all your string literals from, say a file, and give the memory back to OS when the strings are not used any more, there may be some way to reduce memory footprint (but it will probably slow the program much).

But there is probably many other ways to reduce memory consumption before doing that kind of thing.

Upvotes: 0

Puppy
Puppy

Reputation: 146910

Your program operates on the same literal every time. There is no more efficient form of storage. A std::string would be constructed, duplicated on the heap, then freed every time the function runs, which would be a total waste.

Upvotes: 9

Related Questions