C++ std::allocator 與new對比效率使用


基礎知識通道:http://blog.csdn.net/Xiejingfa/article/details/50955295

 

C/C++:

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 
 5 #define allocate_length 100000
 6 
 7 
 8 int main()
 9 {
10 
11     //allocator比new快的原因:分離分配和初始化這兩個操作allocator少執行一步,new則一般執行兩次(初始化和賦值);
12 
13 
14     std::clock_t start = 0, end = 0;
15 
16     start = clock();
17     std::string *str1 = new std::string[allocate_length];
18     auto str6=str1;
19     for (int i = 0; i < allocate_length; i++)
20     {
21         *str1++ = "Hello World";
22     }
23 
24     delete []str6;
25     end = clock();
26     std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;
27 
28 
29 
30 
31     start = clock();
32     std::allocator<std::string> str_allocate;
33     std::string *str3 = str_allocate.allocate(allocate_length); //分配20個string原始內存
34     auto str4=str3;
35 
36     //方法一:使用默認構造
37     for (int i = 0; i < allocate_length; i++)
38     {
39         str_allocate.construct(str3++,"Hello World");
40     }
41 
42     //方法二:使用allocator的伴隨算法(分別是帶n與不帶)
43     //其他算法:std::uninitialized_copy(iterator begin,iterator end,T value);
44 
45     //std::uninitialized_fill_n(str3,allocate_length,"Hello World");
46 
47 
48     //str_allocate.destroy()調用對象的析構,但是內存還是由allocator控制,需要自己釋放
49     str_allocate.deallocate(str4,allocate_length);
50     end = clock();
51 
52     std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;
53 
54 
55     return 0;
56 }

 


免責聲明!

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



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