为什么堆和栈上面创建对象的时间差距这样大?
时间:2010-08-28
来源:互联网
- //============================================================================
 - // Name        : helloworld.cpp
 - // Author      :
 - // Version     :
 - // Copyright   : Your copyright notice
 - // Description : Hello World in C++, Ansi-style
 - //============================================================================
 - #include <cstdio>
 - #include <ctime>
 - #include <cstdlib>
 - #include <iostream>
 - #include <list>
 - using namespace std;
 - 
        
 - class Object{
 - public :
 -         Object() : i(0),n1(0){
 -         }
 - 
        
 -         void foo(){
 -                 cout<<"foo():"<<i<<endl;
 -         }
 -         ~Object(){
 -         }
 - 
        
 -         Object& operator +=(int i)
 -         {
 -            this->i += i;
 -            return *this;
 -         }
 - private:
 -         int i;
 -         const int n1;
 -         static int n2;
 - };
 - 
        
 - int Object::n2 = 0;
 - 
        
 - int main() {
 -         clock_t start,finish;
 -         start = clock();
 -         for(int i=0;i<10000000;++i){
 -                 new Object();
 -         }
 -         finish = clock();
 -         cout<<"heap "<<(finish - start)<<" ms."<<endl;
 - 
        
 -         start = clock();
 -         for(int i=0;i<10000000;++i){
 -                 Object obj;
 -         }
 -         finish = clock();
 -         cout<<"stack "<<(finish - start)<<" ms."<<endl;
 -         return 0;
 - }
 
heap 1700 ms.
stack 146 ms.
作者: evaspring 发布时间: 2010-08-28
             主要的时间耗子 分配内存 上
栈比堆快,但快不了这么多
            栈比堆快,但快不了这么多
作者: bruceteen 发布时间: 2010-08-29
             显然的, 一个硬件调整栈指针(说不定那个循环根本就没调整过), 一个软件实现堆。
试试:
  
    复制代码
btw, clock()是和CLOCKS_PER_SEC搭配使用的。            
            试试:
- Object* o = static_cast<Object*>(operator new(sizeof *o));
 - for (...)
 - {
 -       new (o);
 -       o->~Object();
 - }
 
作者: OwnWaterloo 发布时间: 2010-08-29
             for(int i=0;i<10000000;++i){
Object obj;
}这里应该只有一次,试试在构造函数里面加个打印,看有几次
            Object obj;
}这里应该只有一次,试试在构造函数里面加个打印,看有几次
作者: hellioncu 发布时间: 2010-08-29
 相关阅读 更多  
      
    热门阅读
-  
 office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
          阅读:74
 -  
 如何安装mysql8.0
          阅读:31
 -  
 Word快速设置标题样式步骤详解
          阅读:28
 -  
 20+道必知必会的Vue面试题(附答案解析)
          阅读:37
 -  
 HTML如何制作表单
          阅读:22
 -  
 百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
          阅读:31
 -  
 ET文件格式和XLS格式文件之间如何转化?
          阅读:24
 -  
 react和vue的区别及优缺点是什么
          阅读:121
 -  
 支付宝人脸识别如何关闭?
          阅读:21
 -  
 腾讯微云怎么修改照片或视频备份路径?
          阅读:28
 















