您的位置:首页 > 其它

前置++i和后置的i++效率探究

2016-03-15 21:27 281 查看
网上看到,说前置++比后置++效率高,个人觉得都是对变量加1,效率应该没有区别,于是在vs2010中探索一番,特在此记录,如有不妥,欢

迎拍砖。

1. 仅对内置数据类型自加,两者效率一样

#include "stdafx.h"
#include <stdio.h>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
int a=1,b=2;
int c,d;
a++;
++b;
return 0;
}


汇编代码如下:



可见,前置加加和后置加加都有三个步骤:

(a)从内存中,拷贝数据到寄存器

(b)寄存器值加1

(c)从寄存器中,拷贝数据到内存

2. 非内置数据类型,前置++比后置++效率高

代码如下:

#include <stdio.h>
#include <iostream>

using namespace std;

class Point        //定义一个点类
{
public:
int x,y;
public:
Point& operator=(Point& hpoint)        //赋值运算符
{
x = hpoint.x;
y = hpoint.y;
cout<<"assign operator"<<endl;
return *this;
}
Point(int _x,int _y):x(_x),y(_y)      //构造函数
{
cout<<"constructor"<<endl;
}
Point()                               //默认构造函数
{
x = 0;
y = 0;
cout<<"constructor"<<endl;
}
Point(Point& ptem)                    //拷贝构造函数
{
x = ptem.x;
y = ptem.y;
cout<<"copy constructor"<<endl;
}
~Point()
{
cout<<"deconstructor"<<endl;
}
//参数int没有实际的意义,仅表示后置加加,返回对象
Point operator++(int);
//前置加加,返回对象的引用
Point& operator++();
};

Point& Point::operator++()    //前置
{
x++;
y++;
return *this;
}

Point Point::operator++(int)  //后置
{
Point tem;                //局部变量
tem = *this;
cout<<"In late plusplus"<<endl;
++(*this);
return tem;
}

int _tmain(int argc, _TCHAR* argv[])
{
Point pt(2,5);
cout<<"前置++"<<endl;
++pt;
cout<<"后置++"<<endl;
pt++;
cout<<pt.x<<" "<<pt.y<<endl;
cout<<"over!"<<endl;
return 0;
}


运行结果如下:



由上可知:

(a)前置++返回的是自身的引用(返回引用可以用于链式运算)

(b)后置++,多生成了两个类对象,一个是局部对象tem和返回的临时对象。

所以,对于自定义类型,前置++较后置++效率高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: