Hi I'm Dan
Hi I'm Dan

Reputation: 181

Why are certain types of string concatenation significantly faster than others?

Consider the following four cases:

#include <string>
int main()
{
    std::string s("Hi I'm Da");

 1. s += "n";
 2. s += 'n';
 3. s = s + "n";
 4. s = s + 'n';

    return 0;
}

Running this test suite with the invocation:

g++ -std=c++11 -O3 -DVER=case -Wall -pedantic -pthread test.cpp -o test

using g++ version 4.8.3 20140624, I get the following results:

2.16172ms
0.48296ms
510.202ms
510.455ms

Now I can understand that += is faster because you don't make a copy with + before assignment, but why does cases 1 and 2 show a significant difference compared to cases 3 and 4? Also, how does using double quotes or single quotes affect the concatenation speed?

Upvotes: 12

Views: 225

Answers (1)

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

s += "n";

This operates on the string in-place. There is possibility that memory reallocation will not be required. But string literals are zero-terminated character sequences, so the code needs to find the 0 value in memory after 'n'.

s += 'n';

This is similar to the first one, but it uses character literal instead of string literal. No need for searching for 0, so it may be faster.

s = s + "n";

Search for 0 is there, but what is more - much more - new temporary string object must be constructed, and most likely it means memory allocation, which is order of magnitude or more costly.

s = s + 'n';

May be faster than the previous one, but the difference caused by searching for 0 most probably is negligible compared with temporary object creation and allocation on the heap.

Note all "probably" and "may be". What I described may happen in popular compilers, but various optimisations may change the picture entirely.

Upvotes: 5

Related Questions