If I have var x: CustomType?
, what is the performance hit when using unwrapping x!
?
Is there meaning of writing following:
if let x1 = x {
f(x1)
f2(x1)
}
or with the same performance I could write:
f(x!)
f2(x!)
NOTE: I know that in the first case there is checking if the optional is valid, but what if I know that this optional is 100% valid in this code?
Unless you are compiling -Ounchecked
(and don’t), they are going to end up very similar, because the runtime is still going to check if the optional contains a value either way (because if you force-unwrap a nil value, you get a runtime assertion, it doesn’t just access the memory as if it weren’t nil). Something that might give if let
an edge is that you are telling the compiler more about what you are trying to do, which gives it a better chance of optimizing it.
However, instead of worrying about this, take all the thought effort of wondering which is faster, and more importantly, all the time you spent reasoning about whether it’s safe to use !
because your variable definitely probably almost certainly isn’t going to be nil (oops except that one time), and put it to better use.
Instead put that time into optimizing the stuff that actually matters. Look for where you are doing things in O(n^2)
when you could be doing them in O(n log n)
. Think about cache locality. Think about doing more at compile-time over run-time. Don’t fuss about something that might be costing you one CPU instruction more than a safer alternative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With