string 与 c style 字符串的效率测试
?無(wú)意中看見(jiàn)c++ string與 c char字符串效率的一些爭(zhēng)論。
因而就工作中常用到的語(yǔ)句, 自己寫(xiě)了一些比較公平的測(cè)試代碼, 基本可以看出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è)試結(jié)果如下:
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è)試時(shí)發(fā)現(xiàn)c++ string給出的時(shí)間有時(shí)候?yàn)?, 可能與string 內(nèi)部設(shè)計(jì)相關(guān)
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的string 与 c style 字符串的效率测试的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。