日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

string 与 c style 字符串的效率测试

發(fā)布時(shí)間:2025/3/21 编程问答 54 豆豆
生活随笔 收集整理的這篇文章主要介紹了 string 与 c style 字符串的效率测试 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

?無(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。