string 与 c style 字符串的效率测试
?無意中看見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 內部設計相關
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的string 与 c style 字符串的效率测试的全部內容,希望文章能夠幫你解決所遇到的問題。