How efficient is functional programming C++?
Hey guys,
So, I've been wondering... What if I started taking a more functional approach and started using std::function instead of just invoking functions. Like, if I started composing std::function objects and passing them around and other stuff like that (I know, such ambiguity), would I see a performance hit?
JavaScript is neat in the sense that everything is an object so functional programming is very highly encouraged. I've been trying to introduce the JS library Ramda into my code more and it got me thinking about designing my C++ in a similar matter.
For example, what if I wanted to design a function that would in essence be,
Code:
std::atomic_flag lock = ATOMIC_FLAG_INIT;
template <class R, class... Args> R&& spinLockExecutor(std::function<R(Args...)>& f)
{
while (lock.test_and_set(std::memory_order_acquire)) {
}
R r = f();
lock.clear(std::memory_order_release);
return std::move(r);
}
or something like that.
Would I see a performance hit? I guess it depends on if I keep my function objects alive or create them before calling spinLockExecutor.
Hmm... Is this a good C++ design pattern? I really like the idea of having a function I can just throw another function at and it'll execute with a spinlock mutex. It's really up to the programmer but this is obviously meant for very short functions that need to be executed in an atomic manner and I'm wondering about design patterns and this was one that I like.