"It’s time to upgrade". That’s a common theme you’ll hear if you watch Street Outlaws on the Discovery Channel. Their goal is simple - be the fastest car on the street or it’s time to upgrade. They are continuously looking for ways to boost the performance of their cars (nitrous, turbos, fiberglass panels, etc). Some performance mods are quick and others take time to implement and refine. In this post, let's focus on Swift performance improvements we can implement and release rather quickly. In fact, most of these improvements should only cost a story point or two:
Mark classes final
A final class will explicitly enable static dispatch for all methods which allows the compiler to optimize methods at compile time resulting in more efficient method invocation at runtime. There are two types of method dispatch: static and dynamic. Dynamic dispatch (the default type of method dispatch) is not as efficient because its dispatch isn’t known until runtime. Dynamic dispatch provides runtime conveniences like polymorphism, inheritance, and overloading but incurs a higher performance penalty. Therefore, by simply marking classes final we get a minor performance boost rather quickly. Refer to Apple’s Understanding Swift Performance talk for additional details.
Prefer isEmpty over count > 0
The native isEmpty method is more efficient because it only verifies one element exists where as the count property iterates the entire collection. Want to enforce this efficient practice within your codebase? SwiftLint has a static analysis check for this rule.
Convert strings to enums
In Apple’s Understanding Swift Performance talk they mentioned three dimensions of performance (see Listing 1).
Faster | Dimension | Slower |
---|---|---|
Stack | Allocation | Heap |
Less | Reference Counting | More |
Static | Method Dispatch | Dynamic |
When creating Swift objects it’s important to understand how much an object or property weighs in regards to these three dimensions. For example, a String is not an efficient type because it is allocated on the heap and it incurs a reference count. Comparatively, Enums are much more efficient because they are allocated on the stack, do not incur a reference count, and as a bonus they are type safe resulting in a win-win-win. Interested in automatically converting your localizable strings, asset names, or storyboard names to enums? SwiftGen has accomplished this task nicely on my projects.
Import existing images from the file navigator into an asset catalog
An asset catalog is preferred because it caches images, optimizes memory consumption, and enables lightweight App Store downloads via App Thinning - unnecessary image densities are not downloaded. Xcode has a wizard for automatically importing images into an asset catalog rather quickly. Refer to Apple’s Improving Existing Apps with Modern Best Practices talk for additional details.
Parse JSON on a background thread
This allows the main thread to remain idle to serve other threads while the JSON is transformed to an object. Refer to Apple’s Concurrent Programming with GCD in Swift 3 talk for more details.
let json = [String : Any]()
let dataTrasformQueue = DispatchQueue(label: “my.data.trasform.queue”)
dataTrasformQueue.async {
let result = T(json: json) // Transform JSON to object on background thread
DispatchQueue.main.async {
completionHandler(result) // Return control to main thread after object is parsed
}
}
Prefer structs over classes (until you reach their point of diminishing returns)
Structs have many advantages over classes: they are allocated on the stack, they prevent unintended sharing, their memberwise initializer is a nice convenience, and a struct by itself doesn't incur reference counting. However, a structs properties will incur reference counting when they are reference types like String. Therefore, structs have a point of diminishing returns in regards to reference counting that multiplies proportionally by their number of properties which are reference types. A struct containing more than 2 reference types begins to incur a higher reference count than a comparative class. Refer to Apple’s Understanding Swift Performance talk for additional details.
Rewrite Objective-C objects in Swift
Refactoring Objective-C objects to Swift was the primary theme in Apple’s Optimizing App Startup Time talk. This tip barely makes the list for “busy developers” because the scope of this task may be large depending on your codebase but it’ll become more manageable by focusing on converting one Objective-C class per week or iteration.
Summary
The fastest car doesn't always win. The quickest car from start to finish does. A driver and the adjustments they make to their car has a huge impact on their performance. The tips above are quick adjustments we can make to our Swift code so our apps will be more efficient from point A to point B.
No comments :
Post a Comment