C風格字符串和C++ string 對象賦值操作的性能比較


<<C++ Primer>> 第四版 Exercise Section 4.3.1 部分Exercise 4.2.9 習題如下:

在自己本機執行如下程序,記錄程序執行時間:

 

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 #include <ctime>
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11     clock_t start, end;
12     start = clock();
13     const char *pc = "a very long literal string";
14     const size_t len = strlen(pc);
15     cout << "the length of pc is: " << len << endl;
16     for (size_t ix = 0; ix != 10000; ++ix)
17     {
18         char *pc2 = new char[len+1];
19         strcpy_s(pc2,len+1,pc);
20         if (strcmp(pc, pc2))
21         {
22             // do nothing
23         }
24         delete[] pc2;
25     }
26 
27     end = clock();
28     cout << "for c style operation : " << (end - start) << endl;
29 
30     clock_t start1, end1;
31     start1 = clock();
32     string str("a very long literal string");
33     for (int ix = 0; ix != 10000; ++ix)
34     {
35         string str2 = str;
36         if (str != str2)
37         {
38 
39         }
40     }
41     end1 = clock();
42     cout << "for c++ string operation : " << (end1 - start1) << endl;
43     return 0;
44 }

 

其中時間記錄的代碼是我自己加的,用於分別記錄C風格字符串和C++ string對象賦值操作的執行時間。執行結果如下:

 

 c++ string 對象的賦值操作耗時明顯比c風格字符串要長很多,但是從書上的結論來說,c++ string的操作要遠比c風格字符串長。所以這里記錄下,以后研究標准庫時,分析代碼來找原因。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM