烙印99
以下是增量操作符位于不同转换单元时的基准。编译器与g+4.5。暂时忽略样式问题// a.cc#include <ctime>#include <array>class Something {public:
Something& operator++();
Something operator++(int);private:
std::array<int,PACKET_SIZE> data;};int main () {
Something s;
for (int i=0; i<1024*1024*30; ++i) ++s; // warm up
std::clock_t a = clock();
for (int i=0; i<1024*1024*30; ++i) ++s;
a = clock() - a;
for (int i=0; i<1024*1024*30; ++i) s++; // warm up
std::clock_t b = clock();
for (int i=0; i<1024*1024*30; ++i) s++;
b = clock() - b;
std::cout << "a=" << (a/double(CLOCKS_PER_SEC))
<< ", b=" << (b/double(CLOCKS_PER_SEC)) << '\n';
return 0;}O(N)增量试验// b.cc#include <array>class Something {public:
Something& operator++();
Something operator++(int);private:
std::array<int,PACKET_SIZE> data;};Something& Something::operator++(){
for (auto it=data.begin(), end=data.end(); it!=end; ++it)
++*it;
return *this;}Something Something::operator++(int){
Something ret = *this;
++*this;
return ret;}结果虚拟机上g+4.5的结果(以秒为单位):Flags (--std=c++0x) ++i i++-DPACKET_SIZE=50 -O1 1.70 2.39-DPACKET_SIZE=50 -O3 0.59 1.00-DPACKET_SIZE=500 -O1
10.51 13.28-DPACKET_SIZE=500 -O3 4.28 6.82O(1)增量试验现在让我们来看以下文件:// c.cc#include <array>class Something {public:
Something& operator++();
Something operator++(int);private:
std::array<int,PACKET_SIZE> data;};Something& Something::operator++(){
return *this;}Something Something::operator++(int){
Something ret = *this;
++*this;
return ret;}它在增量中什么也不做。这模拟了增量具有恒定复杂性的情况。结果现在的结果差别很大:Flags (--std=c++0x) ++i i++-DPACKET_SIZE=50 -O1 0.05 0.74-DPACKET_SIZE=50 -O3 0.08 0.97-DPACKET_SIZE=500 -O1
0.05 2.79-DPACKET_SIZE=500 -O3 0.08 2.18-DPACKET_SIZE=5000 -O3 0.07 21.90结语性能方面如果您不需要前面的值,请养成使用预增量的习惯。即使使用内置类型,也要保持一致,如果您用自定义类型替换内置类型,您将不会有遭受不必要的性能损失的风险。语义层面i++说increment i, I am interested in the previous value, though.++i说increment i, I am interested in the current value或increment i, no interest in the previous value..再说一遍,你会习惯的,即使你现在还不习惯。克努斯。过早的优化是万恶之源。这是过早的悲观。