gpt4 book ai didi

c++ - 使用 str += "A"或 str = str + "A"连接字符串之间的性能差异

转载 作者:行者123 更新时间:2023-12-04 11:51:32 29 4
gpt4 key购买 nike

我想知道为什么str += "A"str = str + "A"有不同的表现。
在实践中,

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
根据我的搜索, str = str + "A"必须复制“str”,因此每次迭代串联都需要 O(N)所以如果你迭代 N 次,时间复杂度是 O(N^2) .
然而, str += "A"只是将“A”连接到“str”,因此不需要进行任何复制。所以如果迭代N次,只有 O(N) .
我觉得这很奇怪。当我检查汇编代码时,它们是相同的。我认为编译器翻译 str += "A"str = str + "A"所以结果应该是一样的。
如果你看看实际结果,我错了,但你能告诉我错在哪里吗?
Here is my ref link .
这是我的计时代码:
#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;
}
============================ 我的测试代码。谢谢
enter image description here
enter image description here
enter image description here
enter image description here
enter image description here

最佳答案

i think compiler translates str += "A" to str = str + "A" so the result have to be same.


不, operator+=是一个单独的函数。它不像在 Python 中 - x += y 不是 翻译为 x = x + y .这是一件好事,因为它允许进行优化,从而使您观察到的性能差异。我怀疑程序集是否相同,它是两个具有不同实现的独立函数。
  • operator+= - 没有复杂性,但合理地将每个复制的字符摊销 O(1)。
  • operator+ 显然,O(n) 充其量。

  • x = x+y首先评估右侧,因此编译器必须分配一个新的字符串对象,然后将其移入 xx 中的旧字符串因此被浪费地丢弃。在 as-if 规则下,编译器可以自由替换 x = x+yx+=y但很难说它何时甚至是否会这样做。

    关于c++ - 使用 str += "A"或 str = str + "A"连接字符串之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68962767/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com