DontCareBear
DontCareBear

Reputation: 834

achieving fast performance using polymorphism and functors in c++

I am currently writing a Maya 2013 plugin in c++ that optimizes the geometry of given mesh for specific constraints. i need to achieve maximum performance. for now i only implemented an hard-coded version of the algorithm for a specific constraint and it's very fast, but i need achieve some king of generic implementation of the algorithm for any given constraint (thus i need some kind of polymorphism).

a pseudo code for the general structure of the algorithm is:

(1) do k times:
(2)      for every face fj in the mesh do: 
(3)            some manipulation on the vertices qi incident to the face fj
(4)      for every vertex  vi in the mesh do: 
(5)            some manipulation  on the faces fj incident to the vertex vi 

the problem is that in my specific implementation there is no function calls for the calculations in steps 3 and 5 in the pseudo code, when i tried calculating those steps with auxiliary functions there was a big reduction on performance.

for a generic implementation i need to make function calls in steps 3 and 5 for every constraint.

i thought of two kinds of solutions:

  1. write a generic class for constraints. derive classes for every constraint i need with methods for calculaing steps 3 and 5 in the algorithm.
  2. write a general functor (class with only the () operator) and derive from it functors for calculating steps 3 and 5. the reason for this idea is that the call for the () operator in a functor is inlined (answer about reusable code in this link).

first question:

is there any way to reduce the overhead for the function calls?

second question:

is there any way to make the compiler always inline the functions in the two solutions above? from this question i know that virtual functions called from pointers to objects can't be inlined.

third question:

is there a more efficient way then the solutions i proposed?

Upvotes: 3

Views: 1395

Answers (1)

Anycorn
Anycorn

Reputation: 51465

I would recommend you take look at templates and pass a template function/functor as a parameter.
With dynamic polymorphism you almost always have indirect call to function, ie the body of the function isn't known to compiler - hence optimization options are limited. Templates allow you to do what is called a static polymorphism.

see these links for more info:

Static polymorphism definition and implementation

C++ templates for performance?

Upvotes: 1

Related Questions