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?
Reason being : The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.
The reason is that String is immutable; its value does not change. When adding a string, we create a new string in memory. StringBuilder is mutable, so when we use the append, its value changes, not a new string is created. Therefore using StringBuilder will save memory and run faster.
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.
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.
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