Is it more efficient to create a functor without members of a class or stack object?

I have a functor without member variables. I am wondering if it is more efficient to create this functor on the fly as needed, or to cache it as a member variable. There are problems associated with optimizing a class with an empty base and cache location, which I'm not sure about.

struct Foo { int operator()(const MyData& data) const { ... } }; 
+8
c ++ performance
source share
2 answers

For an empty object, just create it on the stack. Adding a functor to your type as a member will make all your objects larger. Adding it as a base (to use empty base optimization) will lead to a weird design in which your type implements operator()(const MyData&) for no reason. Even if you make it private, the operator will be there.

Since the type has no members, there is no problem with the locality of the cache, since there is no data to access. The main use of the stateless functor is to allow the compiler to embed a function call (compared to a free function of the same name)

+9
source share

The general optimization rule: to make the code work first, optimize it only when it is necessary (in other words, you have profiled your code and found a bottleneck that needs to be fixed in order to significantly improve performance).

0
source share

All Articles