C++中的前置++和后置++的效率问题

测试环境:VS2008

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

#include <iostream>

using namespace std;

int main()
{
    int a=1,b=2;
    a++;
    ++b;
    return 0;
}

汇编代码如下:

    int a=1,b=2;
00F4138E  mov         dword ptr [a],1 
00F41395  mov         dword ptr [b],2 
    a++;
00F4139C  mov         eax,dword ptr [a] 
00F4139F  add         eax,1 
00F413A2  mov         dword ptr [a],eax 
    ++b;
00F413A5  mov         eax,dword ptr [b] 
00F413A8  add         eax,1 
00F413AB  mov         dword ptr [b],eax 
    return 0;

可以看出,前置++的a和后置++的b的操作是一样的·,两者效率一样

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

  • 从内存中,拷贝数据到寄存器 
  • 寄存器值加1 
  • 从寄存器中,拷贝数据到内存 

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

#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 main()
{
    Point pt(2,5);
    cout<<"前置++"<<endl;
    ++pt;
    cout<<"后置++"<<endl;
    pt++;
    cout<<pt.x<<" "<<pt.y<<endl;
    cout<<"over!"<<endl;
    return 0;
}

汇编代码如下:

 ++pt;
0022199B  lea         ecx,[ebp-18h] 
0022199E  call        Point::operator++ (22100Fh) 





    pt++;
002219CE  push        0    
002219D0  lea         eax,[ebp-0F4h] 
002219D6  push        eax  
002219D7  lea         ecx,[ebp-18h] 
002219DA  call        Point::operator++ (22124Eh) 
002219DF  lea         ecx,[ebp-0F4h] 
002219E5  call        Point::~Point (22103Ch) 

运行结果如下:

由上可知: 
(a)前置++返回的是自身的引用(返回引用可以用于链式运算) 
(b)后置++,多生成了两个类对象,一个是局部对象tem和返回的临时对象。

所以,对于自定义类型,前置++较后置++效率高。

猜你喜欢

转载自blog.csdn.net/ijn842/article/details/81239717