Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 214
Victor Parmar Avatar asked Dec 05 '10 22:12

Victor Parmar


2 Answers

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.

like image 158
Puppy Avatar answered Sep 22 '22 03:09

Puppy


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

like image 36
Ben Voigt Avatar answered Sep 23 '22 03:09

Ben Voigt