Preface
With the rapid growth of the internet, users have higher and higher expectations for mobile apps. App launch time is an important metric, and it directly affects user experience. The QQReader app launch flow contains many business modules and also initializes many third-party libraries, which inevitably increases launch time. Therefore, optimizing app launch is very necessary.
Mach-O Files
Before optimization, first understand what a Mach-O file is. The UNIX standard defines a general portable binary file format called ELF. macOS, however, maintains its own binary format: Mach-Object, or Mach-O.
Mach-O File Types
For macOS and iOS, Mach-O is the executable file format. It mainly includes these file types:
- Executable: the main binary of an app.
- Dylib: dynamic library.
- Bundle: cannot be linked directly; loaded at runtime through
dlopen.- Image: includes Executable, Dylib, and Bundle.
- Framework: a folder containing a Dylib, resource files, and header files.
Mach-O Image File Format
A Mach-O image file mainly contains three parts:
- Mach64 Header
- Load Commands
- Section64
Look at the format of a real executable file:

Almost all Mach-O files contain three segments: __TEXT,
__DATA, and __LINKEDIT.
__TEXTcontains the Mach header, executable code, and read-only constants such as C strings. It is read-only and executable,r-x.__DATAcontains global variables, static variables, and so on. It is readable and writable,rw-.__LINKEDITcontains loader metadata, such as function names and addresses. It is read-only.
Universal Binary, or Fat Binary
A universal binary is formed by combining Mach-O files for multiple architectures. A Fat Header records the offset of each architecture in the file. QQReader’s executable file is a fat binary:
1 | lingyun@sairyouifus-MBP Desktop$ file QQReaderUI |
iOS App Launch Flow
Kernel Flow for Executables
As shown below, when launching an app, the system eventually calls
two functions based on your action: fork and
execve. fork creates a process;
execve loads and runs a program. There are several related
functions, such as execl, execv, and
exect, each providing different ways to pass arguments and
environment variables to a program. On macOS, all these other exec paths
eventually call the kernel path execve.
- Execute the
execsystem call. Usually this starts by callingfork()to create a new process, and then the process executesexec. Afterfork()creates a new process, the parent and child processes share the code segment, but their data spaces are separate. The parent process copies the contents of its data space, as well as context, into the child process.
- To improve efficiency, the system uses a copy-on-write strategy. When creating the child process, it does not immediately copy the parent process’s address space. The parent and child initially share the same address space. Only when the child process needs to write data, such as writing into a buffer, is the address space copied. After that, the parent and child have independent address spaces. For
fork()followed byexec, this strategy is very efficient. If everything were copied immediately, the child process’s copied data would be discarded afterexecand replaced by the new process anyway.
Key Points in App Launch
According to Apple’s official WWDC session, Optimizing App Startup Time, iOS app launch can be divided into the pre-main stage and the main stage. So total app launch time = pre-main time + main time.
| Stage | pre-main | main |
|---|---|---|
| Flow | Loading system dylibs and the app executable | From entering main until
application:didFinishLaunchingWithOptions: in
AppDelegate finishes. This stage mainly builds the first
screen and completes rendering. |
Borrowing two classic diagrams:
pre-main
main
Measuring QQReader’s pre-main Time
Add the DYLD_PRINT_STATISTICS Option
Measurement Results
Cold launch time:
Warm launch time:
The Dynamic Linker: dyld
What Is dyld?
Dynamic library loading is mainly completed by dyld,
Apple’s dynamic linker.
The system first reads the app executable, a Mach-O file, and obtains
the path to dyld from it. It then loads dyld.
dyld initializes the runtime environment, enables cache
strategies, loads the program’s dependent libraries, including our
executable file, links those libraries, and finally calls the
initialization methods of each dependency. At this step, the runtime is
initialized.
After all dependent libraries are initialized, the final executable
file is initialized. At this point, the runtime initializes class
structures for all classes in the project and calls all
+load methods. Finally, dyld returns the
address of the main function, main is called,
and we arrive at the familiar program entry point.
dyld Shared Cache
When you build a real program, it links against many different libraries. Those libraries depend on other frameworks and dynamic libraries. The number of dynamic libraries that need to be loaded can be large, and the number of mutually dependent symbols can be even larger. Thousands of symbols may need to be resolved, which takes time.
To reduce the time spent in this process, the dynamic linker
on macOS and iOS uses a shared cache. The macOS shared cache is located
under /private/var/db/dyld/, while iOS uses
/System/Library/Caches/com.apple.dyle/.
For each architecture, the operating system has a separate file containing most dynamic libraries. These libraries have already been linked into one file, and symbol relationships between them have already been processed. When loading a Mach-O file, either an executable or a library, the dynamic linker first checks whether it exists in the shared cache. If it does, it can be used directly from the shared cache. Each process maps this shared cache into its own address space. This greatly optimizes program launch time on macOS and iOS.
dyld Loading Process
The dyld loading process mainly includes the following steps.
Load dylibs image
When loading each dynamic library, dyld needs to:
- Analyze dependent dynamic libraries.
- Find the Mach-O file for the dynamic library.
- Open the file.
- Validate the file.
- Register the file signature with the system kernel.
- Call
mmap()for each segment of the dynamic library.
Usually, an app needs to load many dylibs. System libraries are optimized and can be loaded quickly. App-dependent dylibs may depend on other dylibs, so the dynamic libraries dyld needs to load form a recursive dependency set.
Optimization directions for this step:
- Reduce dependencies on non-system libraries.
- Merge non-system libraries.
Look at the shared dynamic libraries used by QQReader.
Command: otool -L QQReaderUI
Rebase/Bind image
Because of ASLR, or address space layout randomization,
the load addresses of executables and dynamic libraries in virtual
memory are not fixed across launches. Therefore, rebase and bind are
needed to fix resource pointers inside the image so that they point to
the correct addresses.
Rebase fixes pointers that point to resources inside the current image. Bind fixes pointers that point to resources outside the image.
Rebase happens first. It needs to read the image into memory and perform encrypted validation by page to ensure it has not been tampered with, so the bottleneck is I/O. Bind happens afterward. Since it needs to query symbol tables to point to cross-image resources, and the image has already been read and verified during rebase, the bottleneck is CPU computation.
The key optimization for this stage is reducing the number of
pointers in the __DATA segment. We can optimize by:
- Reducing the number of Objective-C classes and selectors.
- Reducing the number of C++ virtual functions.
Several concepts are worth clarifying:
- ASLR, address space layout randomization. 1. Traditionally, each process launch uses a fixed and predictable layout. This means the initial virtual memory of a given program on a given architecture is basically consistent, and during normal process execution the address layout in memory is highly predictable. This gives attackers more room for code injection and memory rewriting. 2. With ASLR, the address space is lightly randomized at each process launch. It is offset, not completely scrambled. The rough layout, such as program text, data, and libraries, stays the same, but concrete addresses differ, blocking address guessing.
- Rebase is the process of fixing data because a Mach-O image is not loaded at a fixed base address.
- Binding is the process of binding external symbols used by this binary. For example, Objective-C code may use
NSObject, whose symbol is_OBJC_CLASS_$_NSObject. This symbol is not in our binary; it is in the system libraryFoundation.framework, so binding connects the relationship.
lazyBindingmeans binding is not performed immediately when loading a dynamic library. Instead, binding happens the first time the method is called. This is implemented through the symboldyld_stub_binder. The first call to a lazily bound method reachesdyld_stub_binder, which finds the real method and binds the address to the stub, so later calls no longer need binding.
Objc setup
Objc setup is mainly completed in
objc_init. objc_init is reached after
libsystem_initializer, an initialize method in
libsystem, initializes libdispatch; then
libdispatch_init calls _os_object_int, which
eventually calls _objc_init.
1 | void _objc_init(void) |
In _objc_init, the runtime registers three callbacks
with dyld: map_2_images, load_images, and
unmap_image.
- After dyld finishes the
bindingoperation, it sends thedyld_image_state_boundnotification. The callback bound to it,map_2_images, is then called. It mainly completesObjc Setupby doing these things: 1. Read theDATAsegment of the binary and find Objective-C related information. 2. Register Objective-C classes. 3. Ensure selector uniqueness. 4. Read protocol and category information.
load_imagescalls Objective-C+loadmethods. It listens for thedyld_image_state_dependents_initializenotification.
unmap_imagecan be understood as the reverse operation ofmap_2_images.
initializers
The previous three steps are static adjustments. They modify data in
the __DATA segment. This step begins dynamic adjustment and
starts writing into the heap and stack. The main work includes:
- Objective-C
+load()functions.
- C++ constructor attribute functions, such as
attribute((constructor)) void DoSomeInitializationWork().
- Creation of non-trivial C++ static global variables, usually classes or structures. If their constructors do heavy work, launch speed suffers.
Objective-C +load methods and C++ static constructors
execute from bottom to top, ensuring each executed method can find the
dynamic libraries it depends on.
- dyld starts initializing the program binary.
ImageLoaderreads the image, which contains our classes, methods, and other symbols.
- Because runtime has registered callbacks with dyld, after the image is loaded into memory, dyld notifies runtime to process it.
- Runtime takes over and calls
mapimagesto parse and process the image. Thenloadimagescallscallloadmethods, traversing all loaded classes and calling each class’s+loadmethod and its categories’+loadmethods in inheritance order.
The whole process is led by dyld. After initializing the
runtime environment, it works with ImageLoader to load the
binary into memory according to the Mach-O format, dynamically links
dependent libraries, and lets runtime load Objective-C-defined
structures. After all initialization work ends, dyld calls
the real main function.
Borrowing an explanation of static constructors from this excellent blog:
constructor and +load are both called
before main, but +load is called slightly
earlier than constructor. When dyld loads an image, which
can be understood as a Mach-O file, it first notifies the Objective-C
runtime to load all classes in it. As each class is loaded, its
+load is called. Only after all classes are loaded does
dyld call all constructor methods in that image.
So constructor is a perfect opportunity to do
mischief:
- All classes have already been loaded.
mainhas not executed yet.- Unlike
+load, it does not need to be attached to a class.
pre-main Stage Optimization
1. Delete unused code: unused static variables, classes, and methods
You can use AppCode to scan the project and delete unused code such as:
- Unused local variables.
- Unused parameters.
- Unused values.
2. Abstract duplicated code
- In iOS code, many category methods may be written for the same class. When there are many developers involved, duplicate methods may appear. At runtime, only one category method can be called, depending on which category is loaded later. However, both methods still exist in the compiled binary. This increases app size and launch time, so this kind of duplication should be avoided.
- In many places, function names may differ while the actual functionality is the same. This is harder to discover and requires attention while writing code.
- Or two functions may have similar names and contain many similar code blocks. In that case, common code should be extracted.
3.
Move work from +load to +initialize, or avoid
heavy work in +load
+load is called during launch, while
+initialize is called when a class is first used. But if
you move logic from +load to +initialize, be
careful about repeated calls to +initialize.
4. Reduce unnecessary frameworks, or optimize existing frameworks
For example, QQReaderUI LinkMap analysis can show which files or third-party libraries occupy large amounts of space, providing direction for optimization.
1 | Path: /Users/lingyun/Library/Developer/Xcode/DerivedData/QQReaderUI-ipad-akzqsuuhhnlhdigisyuqwzvuwrfy/Build/Products/Debug-iphoneos/QQReaderUI.app/QQReaderUI |
Use WMLinkMapAnalyzer to analyze the LinkMap file.
This file helps you understand the compiled state of the whole app.
It may reveal anomalies, and it can also be used to calculate the size
occupied by static libraries in the project. Sometimes a project links
many third-party libraries and the app size grows a lot. If we want to
know exactly how much space each library uses, LinkMap gives us a useful
optimization direction. Because LinkMap contains size data for every
object file, every method, and every data item, we can write a script to
sum the size of each .o file. The sum of .o
files belonging to a static library is the size that library occupies in
the app.
Module sizes, sorted from large to small:
1 | Core1(xxxx1.o) 256.00M |
Then the concrete optimization modules can be chosen based on the analysis result.
main Stage Optimization
This stage refers to the time from entering main to
completing the rendering of the first screen. The optimization goal is
to reduce the time from main to first-screen appearance.
There are two main angles.
didFinishLaunchingWithOptions
Generally, an app does the following work inside
didFinishLaunchingWithOptions:
- Logging and analytics.
- Configuring the environment needed by the app.
- Integrating third-party SDKs.
- …
If some of this work is unnecessary, or can use lazy loading, then
optimization is needed. QQReader has more than 30 startup modules in
didFinishLaunchingWithOptions. The six slowest modules
account for nearly 86% of the time. We analyzed these six modules one by
one, and optimized modules such as font loading and event reporting by
using lazy loading.
First-screen Rendering Optimization
- Avoid xib or storyboard; use code directly.
- In
viewDidLoadandviewWillAppear, try to do less work, do it later, avoid doing it, or make it asynchronous.
- When the home page logic is complex, use Instruments
Time Profilerto find time-consuming bottlenecks.
Coding Notes
- During version iteration, if business requirements change and related code changes as well, old code and old resources should usually be removed. Old resources increase app size, and old code increases executable size, which may also increase the number of Objective-C classes or selectors.
- Abstract duplication and refactor continuously. This reduces executable size and improves maintainability. Reuse UI as much as possible. Before adding a feature, first check whether it already exists in the codebase. Refactor more and use inheritance or composition to reduce code size.
- Be especially careful when writing startup-related business modules. Identify which logic can be delayed or lazily loaded.
- Do not make class and method names too long. On iOS, every class and method name stores a corresponding string value in the
__cstringsegment, so name length affects executable size. The reason is Objective-C’s dynamic nature: classes and methods need to be found by name through reflection, so the object model stores those class and method name strings.
Summary
This article explains the optimization process more from a theoretical perspective. The practical part involves QQReader’s business logic, so screenshots are not convenient to include. But that does not affect our understanding of launch optimization. Let us keep improving together.