在C++ 11:
string s = std::to_string(42);
我做了基準幾個星期前,並得到了這些結果(使用鐺和的libC++隨電流的Xcode):
stringstream took 446ms
to_string took 203ms
c style took 170ms
隨着以下代碼:
#include <iostream>
#include <chrono>
#include <sstream>
#include <stdlib.h>
using namespace std;
struct Measure {
chrono::time_point<chrono::system_clock> _start;
string _name;
Measure(const string& name) : _name(name) {
_start = chrono::system_clock::now();
}
~Measure() {
cout << _name << " took " << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - _start).count() << "ms" << endl;
}
};
int main(int argc, const char * argv[]) {
int n = 1000000;
{
Measure m("stringstream");
for (int i = 0; i < n; ++i) {
stringstream ss;
ss << i;
string s = ss.str();
}
}
{
Measure m("to_string");
for (int i = 0; i < n; ++i) {
string s = to_string(i);
}
}
{
Measure m("c style");
for (int i = 0; i < n; ++i) {
char buff[50];
snprintf(buff, 49, "%d", i);
string s(buff);
}
}
return 0;
}
你的例子沒有意義,爲什麼不只是'std :: string myStr(「TROLOLOLOL」);'?或者你想要增加一個字符串? – Praetorian
一些提示在這裏:http://stackoverflow.com/questions/3799595/itoa-function-problem – PiotrNycz
「可怕的運行時間」的爭論是胡說八道。我已經測試過,發現在某些場合可能會有10%的差異,如果你想要設置一個緩衝區並且不要做太過頭腦的事情。 – cHao