Friday, May 22, 2009

(Function Objects)Functor are faster than Functions

In my play with my pet project, I observed that functors are slightly faster that functions -- I had thought the other way around.

Here the explanation I found online:

"... consider using function objects instead of functions is faster code. The difference between a function and an object of a class that defines the member operator()() is that functions are converted to pointers when passed as arguments to other functions, thus incurring the overhead of a function call even if they are declared inline. In many cases an invocation of a function object, as in the examples on std::transform() in Section 3.2.2.1, can be expanded in-line, eliminating the overhead of a function call."

No wonder.

Wednesday, May 6, 2009

bool guard

Sometimes we need to write code like this to monitor a process
void func()
{
is_finished = false);

// do something ...

is_finished = true);
}

since the code must be written in pairs, one at the very beginning, and the other the very end, using C++ RAII idiom is a bit better.
class bool_guard
{
public:
bool_guard(bool& b, bool init_value = true):m_bool(b)
{
m_bool = init_value;
}

~bool_guard()
{
m_bool = !m_bool;
}
private:
bool& m_bool;
};


now, we can write code like this:
void func()
{
bool_guard b(false);
// do something ...
}