Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to make an functor with no members a class member object or a stack object?

I have a functor with no member variables. I am wondering if it is more efficient to create this functor on the fly as needed or cache it as a member variable. There are issues with regards to empty-base class optimization and cache locality that I'm not sure about.

struct Foo
{
int operator()(const MyData& data) const { ... }
};
like image 357
Nathan Doromal Avatar asked Oct 18 '13 13:10

Nathan Doromal


1 Answers

For an empty object, just create it in the stack. Adding the functor to your type as a member will make all of your objects larger. Adding it as a base (to make use of the empty base optimization), will yield 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 cache locality issues, as no data to be accessed. The main use of a stateless functor is to allow the compiler to inline the call to the function (compared with a free function with the same name)

like image 138
David Rodríguez - dribeas Avatar answered Nov 15 '22 19:11

David Rodríguez - dribeas