I was wondering for quite a while how much speed-up one can roughly expect by a policy*Modern C++ Design, A. Alexandrescu, 2001 based design of algorithms in C++ using templates compared to the strategy*Design Patterns, E. Gamma, R. Helm, R. Johnson, and J. Vlissides, 1995 pattern using polymorphism. Thereby, I am especially interested in algorithms for image processing.
Strategy vs. Policy in C++ Both, policy and strategy, can be used to modularize algorithms. For more details I refer to the textbooks listed below. To compare both approaches exclusively in terms of speed, I created a simple example. I consider the binary operations addition and subtraction of two images pixel-wise and in place for all image pixels i. For the polymorphism based strategy pattern I use an abstract super class. ```cpp template struct BinaryOperator { virtual t_data sBinOperation(t_data a, t_data b) = 0; }; template struct Add : BinaryOperator { t_data sBinOperation(t_data a, t_data b) { return a+b; } }; template struct Subtract : BinaryOperator { t_data sBinOperation(t_data a, t_data b) { return a-b; } }; Further, I have a class that iterates over the image and applies the binary operation pixel-wise. The binary operation is contained as a polymorphic member. ```cpp template <class t_data> struct ImBinaryOperatorStrategy { BinaryOperator<t_data> *binOp; ImBinaryOperatorStrategy(BinaryOperator<t_data> *binOp):binOp(binOp){} void imBinOperation(t_data* im1, t_data* im2, int width, int height, int step1, int step2) { for (int y=0; y<height; y++) for (int x=0; x<width; x++) im1[x+y*step1] = binOp->sBinOperation(im1[x+y*step1],im2[x+y*step2]); } }; For the policy based design with templates, I use the classes Add and Subtract (but not their base class BinaryOperator) and the following class to operate on images. In contrast to the strategy pattern, the binary operation is not a member but passed as template parameter.
...