我正在寻找最优雅的方法将字符串向量内部转换为字符串.以下是我现在使用的解决方案:
static std::string& implode(const std::vector<std::string>& elems, char delim, std::string& s)
{
for (std::vector<std::string>::const_iterator ii = elems.begin(); ii != elems.end(); ++ii)
{
s += (*ii);
if ( ii + 1 != elems.end() ) {
s += delim;
}
}
return s;
}
static std::string implode(const std::vector<std::string>& elems, char delim)
{
std::string s;
return implode(elems, delim, s);
}
Run Code Online (Sandbox Code Playgroud)
那里还有其他人吗?
我发现std::string与老式的以null结尾的字符串相比,s非常慢,速度非常慢,以至于它们将整个程序的速度降低了2倍.
我预计STL会变慢,我没有意识到它会慢得多.
我正在使用Visual Studio 2008,发布模式.它显示字符串的char*赋值比赋值慢100-1000倍(测试char*赋值的运行时非常困难).我知道这不是一个公平的比较,指针赋值与字符串复制,但我的程序有很多字符串赋值,我不确定我可以在所有地方使用" const引用 "技巧.通过引用计数实现,我的程序可以很好,但这些实现似乎不再存在.
我真正的问题是:为什么人们不再使用引用计数实现,这是否意味着我们都需要更加谨慎地避免std :: string的常见性能缺陷?
我的完整代码如下.
#include <string>
#include <iostream>
#include <time.h>
using std::cout;
void stop()
{
}
int main(int argc, char* argv[])
{
#define LIMIT 100000000
clock_t start;
std::string foo1 = "Hello there buddy";
std::string foo2 = "Hello there buddy, yeah you too";
std::string f;
start = clock();
for (int i=0; i < LIMIT; i++) {
stop();
f = foo1;
foo1 = foo2;
foo2 = f;
}
double …Run Code Online (Sandbox Code Playgroud)