Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead of using classes for matrix of algebraic structures in C++

I am using C++ to code some complicated FFT algorithm, so I need to implement such algebraic structures as quaternions and Hamilton-Eisenstein codes. Algorithm works with 2D array of that structures. What would be the overhead of implementing them as classes? In other way, should I create the array with [M][N] dimensions which consists of Quaternion classes, or should I create [M][N][4] array and work with [4] arrays as quaternions? Using classes is more convenient, but creating M*N classes and accessing their methods instead of working with just array - wouldn't that be too much overhead? I'm coding the algorithm for large images processing, so performance is important for me.

like image 949
user517893 Avatar asked Dec 24 '10 10:12

user517893


2 Answers

IMHO you are better served by implementing them as classes simply because this will let you write your code quicker with less errors. You should do measurements to see what performs best if that is important for you, but also make sure that it is actually this code that is the performance bottleneck. (Mandatory Donald Knuth quote: "premature optimization is the root of all evil").

Most compilers will do a very good job at optimizing code for you, I would say. More often than not I find that it is something else than these low level things that make a difference, like adding an early-out test or minimizing the dataset or whatnot.

For a quaternion, you can still implement the class using an array internally (in case that is actually faster), which should make the difference even less important.

You are probably better served by for instance making sure that you can run your algorithms in parallell on multicore machines or make your actual calculations use SSE instructions.

like image 108
villintehaspam Avatar answered Sep 29 '22 07:09

villintehaspam


Regarding overhead of classes: Unless your classes have virtual functions, there's no penalty for using classes.

So, for example, an array of complex variables may be written as:

std::complex<double> m[10][10];

Beware of STL collection classes, though, as they tend to use dynamic allocation and sometimes introduce significant overhead (i.e., I wouldn't make arrays using vector< vector<> >.

You might want to investigate the use of a library such as Eigen for fast, optimized, matrix/vector classes.

like image 23
nimrodm Avatar answered Sep 29 '22 05:09

nimrodm