by makecheck · 9y ago · 0 comments
Additionally, when using Either the lambdas are in the caller and are invoked almost immediately by map. The scope is small and they do not enter into any other compilation unit. If you pass them into the called function, the compiler is only going to be able to optimize them if the called function can be inlined. Even then, the optimizer will have to be smarter, because the error handler will travel through a much larger scope and a type conversion.
The pointer dereference and call overhead is not big and error handling code is supposed to be cold anyway.
It works well when combined with the some usual techniques like the error singletons and exceptions. You can also set an error code you need by capturing the result variable. Or just do what you need in the handler itself.
Returning a special type is about as annoying as returning and handling an error code.
- Callback-oriented programming is its own deep can of worms. What do you want to inline where? In case of leftMap, it's easy for a compiler to inline flatMap, because it's small. What if you're providing a lambda to a huge function? What about variable captures? Really, we've been there with JavaScript.
- It will either incur a yuuge runtime overhead or will require a new calling convention.
- What if you want to transform your data multiple times? Will you use nested lambdas?
IMO, using sum types is the best solution to this problem. Sum types are not "weird special type", they don't require "weird calling convention", C++ is weird for NOT supporting them.
What runtime overhead, a function call? Pointer dereference? Even template magic on the error monad type won't save you from that one. The problem is shifted to the dereference. There you get either to handle an exception or error code, or explicitly check the state of the object.
Nested lambdas do work reasonably well.
But remember, were generally talking about error handling, not a callback that is supposed to run big transforms.
At worst the overhead is a function call anyway and inhibition of inlining in the error path. Generally nothing to worry about.
But not in the standard library. Of course, in C++, you can do anything if you venture outside the standard.