Improve Swift project compile time
After reading “Profiling your Swift compilation times” I decided to try it for our project, as it's about 80% Swift and a couple of Objective-C frameworks. Frankly, dry compile time (after cleaning) is just really bad, pushing 3 minutes. Most of the time compilation is incremental and takes much less time, but the project has to be cleaned several times a day anyway, and the compile times add up.
If the linked post ever goes away, you can profile your project simply by adding the following to your Other Swift Flags in Build Settings for the intended target:
After that you do the following to get the output file culprits.txt with sorted function compile times:
xcodebuild -workspace Project.xcworkspace -scheme Project clean build | grep [1-9].[0-9]ms | sort -nr > culprits.txt
Here's an edited excerpt from our project before I started optimizing:
1172.0ms Views/BeaconMeasurementDataTableViewCell.swift:17:10 func configure(beacon: FilteredBeaconData) 1053.3ms Controllers/ClientViewController.swift:855:20 @IBAction @objc func canvasViewTapped(sender: UITapGestureRecognizer) 994.2ms Helpers/CLLocationDistance.swift:35:17 public func region() -> String? 978.2ms Helpers/CLLocationDistance.swift:35:17 public func region() -> String? 928.3ms Controllers/ClientViewController.swift:855:20 @IBAction @objc func canvasViewTapped(sender: UITapGestureRecognizer) 782.2ms Helpers/CGRectSquare.swift:24:10 func canBeInsetBy(x: CGFloat, y: CGFloat) -> Bool
As you can see, the worst function takes just over a second, and some functions get repeated, so you can edit them once for multiplied benefit. In total, there were about 70 lines with functions taking longer than 100 ms to compile. Here's the before:
$ time xcodebuild -workspace Project.xcworkspace -scheme Project clean build real 15m41.535s user 24m43.824s sys 2m59.478s
I decided to not spend much time on this as we had a different situation than the linked post's author and were not likely to get much improvement. So I edited about 10 worst functions (and found a couple of missed bugs in the process, which is an added benefit). Then I ran the test again:
real 13m7.661s user 22m24.623s sys 2m46.180s
Not much, but that is still a measurable difference: 16.3% for real, 9.4% for user and 7.4% for sys, so about a 10% improvement in total. Not bad for an hour and a half of work.
I also tried comparing the difference in compile time from Xcode when running the app on the simulator, but couldn't come to a definite conclusion: even after cleaning, Xcode compile times vary a lot and the total time stayed around the same 3 minutes. Of course, it's much faster when the libraries and some modules are already cached, usually the build takes no more than 10-15 seconds.
I encourage you to test this for your Swift project if you're disappointed with compile times, it may well be a quick and big win.