jeudi 23 juillet 2015

How to avoid aliasing and improve performance?

In this Stack Overflow answer it is demonstrated that aliasing in C++ can slow down your code. And aliasing in C++ doesn't only apply to pointers, it applies also to references, and more generally to these types specified by the standard. Particularly, there is

an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union)

So according to my understanding, if I have code like below,

 class A{
  public:
   int val;
 };

 void foo(vector<A> & array, int & size, A & a0) {
   for(int i=0;i<size;++i) {
    array[i].val = 2*a0.val;
   }
 }

and it is possible that a0 can alias one of the elements in array, also possibly alias size because of the aforementioned quote, so a0 and size have to be loaded for each iteration resulting in a performance drop.

  1. Then my question is what should I do to the code to avoid the aliasing, and improve the performance?
  2. Passing by const & won't help since it won't avoid aliasing as specified by the standard. Pass a0 by value? But this will make a copying of a0 which I don't like, since in practice, class A may be very complex and copying is a very expensive option.
  3. Is there a general solution to avoid aliasing in C++? If yes, what is it?

Aucun commentaire:

Enregistrer un commentaire