Secret of Swift Performance

Part 1 — Measure

Secret of Swift Performance


There were a lot of discussions about Swift performance.
Is it really faster than C? How can it be faster? What are the speed numbers? etc.

But as an app developer, we want to know how we can make our app faster in an easy way. What is the silver bullet we can easily use to speed up our app.

Identify slow area

It’s important to identify the slow parts of your app. As the 80/20 Rule says, “ about 20% of your app code takes up to 80% of run speed. It means that it’s important to find that 20% part of code that is heavy and improve it, and not the rest of the 80%.
I’ve made a simple function that takes a closure as parameter and measures, run speed of that block of code. Let’s analyze this code.

The measure function takes optional names, it will print it out to console, which helps analyzing logs and a functions of type () -> (). ( it means — takes nothing and returns nothing).
The measure function is pretty simple. It captures time before the function call and after, and prints out the time the function has used.

Let’s measure how much time our code takes. I want to know how much time is taken by a block of code responsible for iteration over an array, and loading an image. We simple wrap those block of code to measure function call. We have used Trailing Closure syntax here, which looks really nice

The result

Array: Time — 0.0845723639995413
Image: Time — 1.77442857499955

Now you know which part takes more time and needs to be improved or moved out of the UI thread.


Always measure speed in Release mode with Optimization Level set to [-Os] or [-Ofast]

Want to Learn More?

Check out “Swift Hight Performance” book