C++ std::allocator 与new对比效率使用

基础知识通道:http://blog.csdn.net/Xiejingfa/article/details/50955295

C/C++:

 #include <iostream>
#include <vector>
#include <string> #define allocate_length 100000 int main()
{ //allocator比new快的原因:分离分配和初始化这两个操作allocator少执行一步,new则一般执行两次(初始化和赋值); std::clock_t start = , end = ; start = clock();
std::string *str1 = new std::string[allocate_length];
auto str6=str1;
for (int i = ; i < allocate_length; i++)
{
*str1++ = "Hello World";
} delete []str6;
end = clock();
std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl; start = clock();
std::allocator<std::string> str_allocate;
std::string *str3 = str_allocate.allocate(allocate_length); //分配20个string原始内存
auto str4=str3; //方法一:使用默认构造
for (int i = ; i < allocate_length; i++)
{
str_allocate.construct(str3++,"Hello World");
} //方法二:使用allocator的伴随算法(分别是带n与不带)
//其他算法:std::uninitialized_copy(iterator begin,iterator end,T value); //std::uninitialized_fill_n(str3,allocate_length,"Hello World"); //str_allocate.destroy()调用对象的析构,但是内存还是由allocator控制,需要自己释放
str_allocate.deallocate(str4,allocate_length);
end = clock(); std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl; return ;
}
上一篇:mybatis逆向工程总结工具类


下一篇:zoom作用