Guard vs If Performance Differences in Conditional Checking and Optional Unwrapping

Rick_HK
Mac O’Clock
Published in
3 min readMay 19, 2020

Xcode often warns me that my function is taking so long to do type-checking. Many of those functions are using ‘Gaurd’ statement. It made me wonder if it would perform better if I switch over to use ‘If’ statement instead.

So I made use of Xcode UnitTest Framework to check which way performs better.

Disclaimer: Guard statement is different from If statement. Guard statement provides different meaning and functionalities that If statement isn't providing. For example, Guard statement will quit the function entirely if the else clause is executed, which provides code clarity and If statement could never provide this feature. I am not saying you should changing the slower one to the faster one only based on the performance, but it is interesting to find out which one is the fastest one for curiosity.

Alright, so I made two testing functions as shown in above picture. I loop through 1 to 9999 and check whether a random integer is an odd number or an even number. I also used UnitTest’s measure function to measure the execution time, which will run the closure 10 times to get the average measurement. In these two functions, there are no other variables except the random integer itself.

The testing device is my 2015’s iPhone 6S. Using real device to do performance test is so much more realistic compared to Mac, because the computing power is based on the iPhone itself, not based on the Mac that you’re using.

The result

Actually this is quite surprising.

guard statement test
if statement test

The Guard statement test only uses 0.118s on average to run; while the If statement uses 0.121s.

So Guard statement is 2.47% faster. It isn’t significant at all.

So how about having a variable? Does it affect the result?

I added an array to each function and try to unwrap it safely.

The result

This time it fits my expectations.

guard statement
if statement

Guard statement’s average execution time is 0.154; while If statement’s average execution time is 0.132

So Guard statement is 16.67% slower than If statement in terms of unwrapping optional. It is quite significant this time.

Conclusion

Although my tests are not very scientific, it is fun to test the differences between these two conditional checking statements. In terms of unwrapping optional, If statement is quite a bit faster than Guard statement. If the If statement fits your function, it is worth considering using it for the performance’s sake.

--

--

Rick_HK
Mac O’Clock

Hi this is Rick from Hong Kong. I am a native iOS and Android mobile developer and also a tech enthusiast. Find me on Twitter https://twitter.com/rick3817