无意中看见c++ string与 c char字符串效率的一些争论。
因而就工作中常用到的语句, 自己写了一些比较公平的测试代码, 基本可以看出string 比 c style字符串高效很多。
#include <iostream> #include <windows.h> #include <string> using namespace std; int main() { unsigned int size = 1000000; char * h1 = new char[size]; memset(h1, 'a', size - 1); h1[size - 1] = 0; char * h2 = new char[size]; memset(h2, 'b', size - 1); h2[size - 1] = 0; char * h3 = new char[size]; memset(h3, 'c', size - 1); h3[size - 1] = 0; char * r1 = new char[ 3 * size + 3]; int e = 0; size_t time = GetTickCount(); e += sprintf(r1 + e, "%s", h1); e += sprintf(r1 + e, "%s", h2); e += sprintf(r1 + e, "%s", h3); time = GetTickCount() - time; cout <<"C style1 time is: " <<time <<" ms." << "length: " << strlen(r1) << endl; e = 0; time = GetTickCount(); e = sprintf(r1 + e, "%s%s%s", h1, h2, h3); time = GetTickCount() - time; cout <<"C style2 time is: " <<time <<" ms." << "length: " << strlen(r1) << endl; string r2; string s1(size - 1, 'a'); string s2(size - 1, 'b'); string s3(size - 1, 'c'); time = GetTickCount(); r2 += s1; r2 += s2; r2 += s3; time = GetTickCount() - time; cout <<"C++ style1 time is: " <<time <<" ms." << "length: " << strlen(r2.c_str()) << " size: " << r2.size() << endl; string r3; time = GetTickCount(); r3 += h1; r3 += h2; r3 += h3; time = GetTickCount() - time; cout <<"C++ style2 time is: " <<time <<" ms." << "length: " << strlen(r3.c_str()) << " size: " << r3.size() << endl; return 0; }
测试结果如下:
C style1 time is: 78 ms.length: 2999997
C style2 time is: 79 ms.length: 2999997
C++ style1 time is: 16 ms.length: 2999997
C++ style2 time is: 15 ms.length: 2999997
其中多次测试时发现c++ string给出的时间有时候为0, 可能与string 内部设计相关