'C++ optional vs throw
The use of optional is more likely when the return value may or may not exist is expected. Exception in other hand is used when something 'unexpected' happens and need to be catch to prevent the system crashes.
Beside the functionality and elegance of these options and focusing only in performance, which code has a better performance in the naïve examples below?
Important to note in my project a Key will be find always, if not I have a big inconsistency and the program need to take several actions...
Optional example:
optional<MyObject> LookUp(const string& Key) {
if (Key_found())
return theObj;
else
return {};
}
int main() {
...
while(true) {
...
optional<MyObject> MyObj = LookUp(Key);
if (MyObj)
//work with MyObj
else
FixInconcistency();
}
}
Throw example:
MyObject LookUp(xonst string& Key) {
if (Key_found())
return the Obj;
throw; //Just throw without any information
}
int main() {
...
while(true) {
...
try {
MyObject MyObj = Lookup(key);
//work with MyObj
} catch (...) {
FixInconcistency();
}
}
}
Solution 1:[1]
As others have noted, the different between the two versions is in the code's meaning, rather than its performance. I understand from the question you are already aware of it, so I'm going to answer the question as asked.
Which one better performs greatly depends on the probability of Key_found returning false.
Exceptions in C++ were built with one goal in mind - make the non-throwing case as cheap as possible, under the understanding that they are thrown in circumstances that are, well, exceptional.
As such, if the probability of Key_found is really low, the extra overhead of returning a compound type over a simple one would make the second form cheaper (assuming, that is, that MyObject is, indeed, simple. Otherwise, there should be little difference).
If, on the other hand, the probability of Key_found is not so low, the cost of repeatedly unwinding the stack would be much higher.
As usual, the best answer is to benchmark.
As a side note, the main advantage of exceptions is that you do not have to explicitly handle the exceptional case inline, and you do not need to propagate it through unwinding. Using it in the way you do here makes little sense.
Also, the throwing sample has a bunch of problems. In particular, throwing nothing doesn't do what you think it does, and a catch(...) without rethrowing is a really bad idea.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
