最优化的串联方式 [英] Most optimized way of concatenation in strings
问题描述
我们每天都遇到很多情况,其中我们必须在我们的代码中执行乏味和非常多的字符串操作。我们都知道字符串操作是昂贵的操作。我想知道哪些是可用版本中最便宜的。
We always came across many situation on daily basis wherein we have to do tedious and very many string operations in our code. We all know that string manipulations are expensive operations. I would like to know which is the least expensive among the available versions.
最常见的操作是连接(这是我们可以在一定程度上控制的东西)。在C ++中连接std ::字符串的最好方法是什么和各种解决方法来加速连接?
The most common operations is concatenation(This is something that we can control to some extent). What is the best way to concatenate std::strings in C++ and various workarounds to speed up concatenation?
我的意思是,
std::string l_czTempStr;
1).l_czTempStr = "Test data1" + "Test data2" + "Test data3";
2). l_czTempStr = "Test data1";
l_czTempStr += "Test data2";
l_czTempStr += "Test data3";
3). using << operator
4). using append()
另外,我们是否可以使用CString over std :: string? / p>
Also, do we get any advantage of using CString over std::string?
推荐答案
这里是一个小测试套件:
Here is a small test suite:
#include <iostream>
#include <string>
#include <chrono>
#include <sstream>
int main ()
{
typedef std::chrono::high_resolution_clock clock;
typedef std::chrono::duration<float, std::milli> mil;
std::string l_czTempStr;
std::string s1="Test data1";
auto t0 = clock::now();
#if VER==1
for (int i = 0; i < 100000; ++i)
{
l_czTempStr = s1 + "Test data2" + "Test data3";
}
#elif VER==2
for (int i = 0; i < 100000; ++i)
{
l_czTempStr = "Test data1";
l_czTempStr += "Test data2";
l_czTempStr += "Test data3";
}
#elif VER==3
for (int i = 0; i < 100000; ++i)
{
l_czTempStr = "Test data1";
l_czTempStr.append("Test data2");
l_czTempStr.append("Test data3");
}
#elif VER==4
for (int i = 0; i < 100000; ++i)
{
std::ostringstream oss;
oss << "Test data1";
oss << "Test data2";
oss << "Test data3";
l_czTempStr = oss.str();
}
#endif
auto t1 = clock::now();
std::cout << l_czTempStr << '\n';
std::cout << mil(t1-t0).count() << "ms\n";
}
在 coliru :
编译以下内容:
clang ++ -std = c ++ 11 -O3 -DVER = 1 -Wall -pedantic -pthread main.cpp
clang++ -std=c++11 -O3 -DVER=1 -Wall -pedantic -pthread main.cpp
21.6463ms
21.6463ms
-DVER = 2
-DVER=2
6.61773ms
6.61773ms
-DVER = 3
-DVER=3
6.7855ms
-DVER = 4
-DVER=4
$ b b
102.015ms
102.015ms
看起来像 2)
, + = code>是获胜者。
It looks like 2)
, +=
is the winner.
(同时编译和不使用 -pthread
)
(Also compiling with and without -pthread
seems to affect the timings)
这篇关于最优化的串联方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!