4.3 Performance of functionsIn the following set of tests, two 3D points are computed on different compilers, using a nonmember friend function, a member function, and a virtual member function, and virtual member function is executed in three cases of single, virtual and multiple inheritance. The following is the nonmember function:
void cross_product (const point2d &PA, const Point3D &PB) {Point3D pc;pc.x = pa.y * pb.z-pa.z * pb.y;pc.y = pA.z * pb.x-pa.x * pb.z;pc.z = pa.x * pb.y-pa.y * pb.x;}
The main () function looks like this (the nonmember function is called):
Main () {Point3D PA (1.725, 0.875, 0.478); Point3D PB (0.315, 0.317, 0.838); for (i = 0; i < 10000000; i++) {pa.cross_product (PA, PB); } return 0;}
If you call a different form of a function, the results are different.
when performing this test in a single inheritance scenario, the execution time of virtual function is significantly increased with each additional layer of inheritanceThe reason: Regardless of the depth of a single inheritance, the code used to invoke the function in the main loop is actually exactly the same, and the same is true for the processing of the coordinate values.
The difference is that the local Point3D class object PC appears in Cross_product (). So the default Point3D constructor was called 10 million times. Increasing the inheritance depth increases the execution cost, which reflects the complexity of the constructor on the PC. This can also explain why multiple inheritance calls have additional burdens.
After you import virtual function, class constructor will get the parameters to set the virtual table pointer. With each additional layer of inheritance, you add an extra vptr setting. In addition, the following test operation is inserted into the constructor, To backtrack compatible c++2.0:
is called in each base and derived class constructor if (This | | this = new (sizeof (*this))//user code goes here
Before importing the new and delete operators, the only way to assume class memory management is to specify the this pointer in constructor.
In these compilers, each additional base class or an additional single inheritance level, its constructor is added to another test of the this pointer. If you perform these constructor 10 million times, the efficiency will drop to the level that can be tested.
the local PC class object, even if not in use, requires a constructor--but can eliminate its constructor invocation by eliminating the use of local objects.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + + object Model--function performance (fourth chapter)