Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the performance hit (if there is any) when unwrapping swift optional types?

Tags:

swift

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?

like image 954
devfreak Avatar asked Feb 11 '23 21:02

devfreak


1 Answers

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.

like image 153
Airspeed Velocity Avatar answered Feb 13 '23 19:02

Airspeed Velocity