Search code examples
c++lazy-evaluationeigen

Eigens lazy evaluation with intermediate variable


In the Eigen documentation, I couldn't find an explanation of the exact circumstances under which an expression will be lazily evaluated. In my case, I'm only interested in coefficient-wise expressions (ie no possibility of aliasing).

For example, given ArrayXXf a(10000, 10000);

a = a.cube() * a.cube();

evaluates for me in ~250ms, the same as

auto aCube = a.cube();
a = aCube * aCube;

whereas

ArrayXXf aCube = a.cube();
a = aCube * aCube;

takes ~550ms to evaluate.

Does assigning an expression to an explicit Array type (such as ArrayXXf) always force it to be evaluated?

The code was compiled with MinGW release -O3.

This is intended as a general question; the example is just made-up.


Solution

  • Generally, yes if you assign an expression to an Array<...> it gets evaluated explicitly (unless the compiler thinks it can optimize away that variable entirely -- that can be the case, especially for small fixed sized arrays.

    Assigning to a auto variable does no evaluation (unless your expression ends with (...).eval()), that also means that aCube * aCube will evaluate each coeffient of aCube twice (although the compiler is likely smart enough to figure out that it can reuse the value). In that particular case it would perhaps be better to write a = aCube.square();