【分析】
i++与++i哪个效率更高?
(1)在内建数据类型的情况下,效率没有区别;
(2)在自定义数据类型Class的情况下,++i效率更高!
自定义数据类型的情况下:++i返回对象的引用;i++总是要创建一个临时对象,在退出函数时还要销毁它,而且返回临时对象的值时还会调用其拷贝构造函数。
【代码】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <stdio.h>
#include <stdlib.h> #include <string.h> #include <vector> #include <iostream> using namespace std; class Integer { public: Integer(int value): v(value) { cout << "default constructor" << endl; } Integer(const Integer &other) { cout << "copy constructor" << endl; v = other.v; } Integer &operator=(const Integer &other) { cout << "copy assignment" << endl; v = other.v; return *this; } // ++i first +1,then return new value Integer &operator++() { cout << "Integer::operator++()" << endl; v++; return *this; } // i++ first save old value,then +1,last return old value Integer operator++(int) { cout << "Integer::operator++(int)" << endl; Integer old = *this; v++; return old; } void output() { cout << "value " << v << endl; } private: int v; }; void test_case() { Integer obj(10); Integer obj2 = obj; Integer obj3(0); obj3 = obj; cout << "--------------" << endl; cout << "++i" << endl; ++obj; obj.output(); cout << "i++" << endl; obj++; obj.output(); } int main() { test_case(); return 0; } /* default constructor copy constructor default constructor copy assignment -------------- ++i Integer::operator++() value 11 i++ Integer::operator++(int) copy constructor value 12 */ |