STL中的容器作為返回值


分別以函數返回值方式和參數傳引用方式測試了vector、map兩種容器,代碼如下:

 1 // testContainer.cpp : Defines the entry point for the console application.
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <vector>
 7 #include <map>
 8 #include <chrono>
 9 using namespace std;
10 vector<int> funcVec1(){
11     vector<int >vec;
12     for (int i = 0; i < 10; ++i){
13         vec.push_back(i);
14     }
15     return vec;
16 }
17 
18 void funcVec2(vector<int>&vec){
19     for (int i = 0; i < 10; ++i){
20         vec.push_back(i);
21     }
22     return;
23 }
24 
25 map<int, int>funcMap1(){
26     map<int, int>tmpMap;
27     for (int i = 0; i < 10; ++i){
28         tmpMap[i] = i;
29     }
30     return tmpMap;
31 }
32 
33 void funcMap2(map<int, int>&tmpMap){
34     for (int i = 0; i < 10; ++i){
35         tmpMap[i] = i;
36     }
37 }
38 
39 int _tmain(int argc, _TCHAR* argv[])
40 {  
41     using namespace std::chrono;
42     steady_clock::time_point t1 = system_clock::now();
43     for (int i = 0; i < 100000; ++i){
44         vector<int> vec1 = funcVec1();
45     }  
46     auto t2 = std::chrono::system_clock::now();
47     //count輸出時鍾周期
48     cout << "return vec takes " << (t2 - t1).count()<<" tick count" << endl;
49     // duration_cast在chrono中,可以將時鍾數轉換為相應的時間間隔
50     cout << duration_cast<nanoseconds>(t2 - t1).count() << " nanoseconds" << endl;
51     cout << duration_cast<microseconds>(t2 - t1).count() << " microseconds" << endl;
52     cout << duration_cast<milliseconds>(t2 - t1).count() << " milliseconds" << endl;
53     cout << duration_cast<seconds>(t2 - t1).count() << " seconds" << endl;
54     cout << " --------------------------------" << endl;
55     vector<int> vec2;
56     for (int i = 0; i < 100000; ++i){
57         funcVec2(vec2);
58     }
59     auto t3 = system_clock::now();
60     cout << "reference vec takes " << (t3 - t2).count() << " tick count" << endl;
61     cout << duration_cast<milliseconds>(t3 - t2).count() << " milliseconds" << endl;
62     cout << " --------------------------------" << endl;
63     for (int i = 0; i < 100000; ++i){
64         map<int,int> tmpMap1 = funcMap1();
65     }
66     auto t4 = system_clock::now();
67     cout << "return map takes " << (t4 - t3).count() << " tick count" << endl;
68     cout << duration_cast<milliseconds>(t4 - t3).count() << " milliseconds" << endl;
69     cout << " --------------------------------" << endl;
70     map<int, int>tmpMap2;
71     for (int i = 0; i < 100000; ++i){
72         funcMap2(tmpMap2);
73     }
74     auto t5 = system_clock::now();
75     cout << "reference map takes " << (t5 - t4).count() << " tick count" << endl;
76     cout << duration_cast<milliseconds>(t5 - t4).count() << " milliseconds" << endl;
77     return 0;
78 }

輸出結果:

在測試代碼中,函數返回值是容器的執行速度比容器作為參數傳遞要慢的多。

可以看到返回容器的函數里,容器頻繁的創建銷毀。

容器作為參數傳遞是項目中常見做法,很少看到函數返回容器。原因就在此。


免責聲明!

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



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