I want to know why str += "A"
and str = str + "A"
have different performances.
In practice,
string str = "cool"
for(int i = 0; i < 1000000; i++) str += "A" // -> approximately 15000~20000 ms
for(int i = 0; i < 1000000; i++) str = str + "A" // -> 10000000 ms
According to what I've looked for, str = str + "A"
have to copy 'str' so each iteration concatenation needs O(N)
so if you iterate N times, time complexity is O(N^2)
.
However, str += "A"
is only concatenating "A" to 'str' so it doesn't need to do any copy. So if iterate N times, only O(N)
.
I think it's weird. When I inspected the assembly code, they were the same. I think compiler translates str += "A"
to str = str + "A"
so the result should be the same.
If you look at the actual results, I'm wrong, but can you tell where I'm wrong?
Here's my code for the timings:
#include<bits/stdc++.h>
#include<chrono>
using namespace std;
using namespace chrono;
int main(void)
{
ios::sync_with_stdio(0);
cin.tie(0);
string str = "aaaa";
system_clock::time_point start = system_clock::now();
for(int i = 0; i < 100000; i++)
{
str = str + "aaaa";
}
system_clock::time_point end = system_clock::now();
microseconds microSec = duration_cast<microseconds>(end-start);
cout << microSec.count() << " ms\n";
return 0;
}