gpt4 book ai didi

c++ - 标准字符串连接性能

转载 作者:行者123 更新时间:2023-11-30 04:05:35 25 4
gpt4 key购买 nike

在性能方面,现代 C++ 编译器中的以下函数之间有什么区别吗?

std::string ConcatA(const std::string& a, const std::string& b, const std::string& c)
{
return a + b + c;
}

std::string ConcatB(const std::string& a, const std::string& b, const std::string& c)
{
std::string r = a;
r += b;
r += c;
return r;
}

最佳答案

ConcatB 有 1 个临时字符串,而 ConcatA 有 2 个临时字符串,因此 ConcatB 快两倍。

$猫cata.cpp

#include <string>
#include <iostream>
std::string ConcatA(const std::string& a, const std::string& b, const std::string& c)
{
return a + b + c;
}
int main(){
std::string aa="aa";
std::string bb="bb";
std::string cc="cc";
int count = 0;
for(int ii = 0; ii < 10000000; ++ii) {
count += ConcatA(aa, bb, cc).size();
}
std::cout<< count <<std::endl;
}

$猫catb.cpp

#include <string>
#include <iostream>
std::string ConcatB(const std::string& a, const std::string& b, const std::string& c)
{
std::string r = a;
r += b;
r += c;
return r;
}
int main(){
std::string aa="aa";
std::string bb="bb";
std::string cc="cc";
int count = 0;
for(int ii = 0; ii < 10000000; ++ii) {
count += ConcatB(aa, bb, cc).size();
}
std::cout<< count <<std::endl;
}

$ clang++ -v

Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.1.0
Thread model: posix

$ clang++ cata.cpp
$ time ./a.out

60000000

real 0m1.122s
user 0m1.118s
sys 0m0.003s

$ clang++ catb.cpp
$ time ./a.out
60000000

real 0m0.599s
user 0m0.596s
sys 0m0.002s
$

关于c++ - 标准字符串连接性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23234327/

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