iOS Launch Optimization

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

iOS Launch Optimization: Mach-O Image File Format (figure 1)

A Mach-O image file mainly contains three parts:

  • Mach64 Header
  • Load Commands
  • Section64

Look at the format of a real executable file:

Mach-O image format

Almost all Mach-O files contain three segments: __TEXT, __DATA, and __LINKEDIT.

  • __TEXT contains the Mach header, executable code, and read-only constants such as C strings. It is read-only and executable, r-x.
  • __DATA contains global variables, static variables, and so on. It is readable and writable, rw-.
  • __LINKEDIT contains 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
2
3
4
lingyun@sairyouifus-MBP Desktop$ file QQReaderUI
QQReaderUI: Mach-O universal binary with 2 architectures: [arm_v7:Mach-O executable arm_v7] [arm64]
QQReaderUI (for architecture armv7): Mach-O executable arm_v7
QQReaderUI (for architecture arm64): Mach-O 64-bit executable arm64

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.

iOS Launch Optimization: Kernel Flow for Executables (figure 3)
    1. Execute the exec system call. Usually this starts by calling fork() to create a new process, and then the process executes exec. After fork() 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.
    1. 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 by exec, this strategy is very efficient. If everything were copied immediately, the child process’s copied data would be discarded after exec and 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

iOS Launch Optimization: pre-main (figure 4)

main

iOS Launch Optimization: main (figure 5)

Measuring QQReader’s pre-main Time

Add the DYLD_PRINT_STATISTICS Option

iOS Launch Optimization: Add the DYLD_PRINT_STATISTICS Option (figure 6)

Measurement Results

Cold launch time:

iOS Launch Optimization: Measurement Results (figure 7)

Warm launch time:

iOS Launch Optimization: Measurement Results (figure 8)

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.

iOS Launch Optimization: dyld Shared Cache (figure 9)

dyld Loading Process

The dyld loading process mainly includes the following steps.

Load dylibs image

When loading each dynamic library, dyld needs to:

  1. Analyze dependent dynamic libraries.
  2. Find the Mach-O file for the dynamic library.
  3. Open the file.
  4. Validate the file.
  5. Register the file signature with the system kernel.
  6. 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:

  1. Reduce dependencies on non-system libraries.
  2. Merge non-system libraries.

Look at the shared dynamic libraries used by QQReader.

Command: otool -L QQReaderUI

iOS Launch Optimization: Load dylibs image (figure 10)

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:

  1. Reducing the number of Objective-C classes and selectors.
  2. Reducing the number of C++ virtual functions.

Several concepts are worth clarifying:

    1. 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.
    1. Rebase is the process of fixing data because a Mach-O image is not loaded at a fixed base address.
    1. 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 library Foundation.framework, so binding connects the relationship.
    1. lazyBinding means 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 symbol dyld_stub_binder. The first call to a lazily bound method reaches dyld_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.

iOS Launch Optimization: Objc setup (figure 11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void _objc_init(void)
{
static bool initialized = false;
if (initialized) return;
initialized = true;

environ_init();
tls_init();
static_init();
lock_init();
exception_init();

_dyld_objc_notify_register(&map_2_images, load_images, unmap_image);
}

In _objc_init, the runtime registers three callbacks with dyld: map_2_images, load_images, and unmap_image.

iOS Launch Optimization: Objc setup (figure 12)
    1. After dyld finishes the binding operation, it sends the dyld_image_state_bound notification. The callback bound to it, map_2_images, is then called. It mainly completes Objc Setup by doing these things: 1. Read the DATA segment of the binary and find Objective-C related information. 2. Register Objective-C classes. 3. Ensure selector uniqueness. 4. Read protocol and category information.
    1. load_images calls Objective-C +load methods. It listens for the dyld_image_state_dependents_initialize notification.
    1. unmap_image can be understood as the reverse operation of map_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:

    1. Objective-C +load() functions.
    1. C++ constructor attribute functions, such as attribute((constructor)) void DoSomeInitializationWork().
    1. 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.

    1. dyld starts initializing the program binary.
    1. ImageLoader reads the image, which contains our classes, methods, and other symbols.
    1. Because runtime has registered callbacks with dyld, after the image is loaded into memory, dyld notifies runtime to process it.
    1. Runtime takes over and calls mapimages to parse and process the image. Then loadimages calls callloadmethods, traversing all loaded classes and calling each class’s +load method and its categories’ +load methods 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.
  • main has 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:

    1. Unused local variables.
    1. Unused parameters.
    1. Unused values.
iOS Launch Optimization: 1. Delete unused code: unused static variables, classes, and methods (figure 13)

2. Abstract duplicated code

    1. 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.
    1. 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.
    1. 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.

iOS Launch Optimization: 4. Reduce unnecessary frameworks, or optimize existing frameworks (figure 14)
1
2
3
4
5
6
7
8
9
Path: /Users/lingyun/Library/Developer/Xcode/DerivedData/QQReaderUI-ipad-akzqsuuhhnlhdigisyuqwzvuwrfy/Build/Products/Debug-iphoneos/QQReaderUI.app/QQReaderUI
Arch: arm64
Object files:
[0] linker synthesized
[ 1] /Users/lingyun/Library/Developer/Xcode/DerivedData/QQReaderUI-ipad-akzqsuuhhnlhdigisyuqwzvuwrfy/Build/Intermediates/QQReaderUI-ipad.build/Debug-iphoneos/QQReaderUI.build/Objects-normal/arm64/XXXX1.o
[ 2] /Users/lingyun/Library/Developer/Xcode/DerivedData/QQReaderUI-ipad-akzqsuuhhnlhdigisyuqwzvuwrfy/Build/Intermediates/QQReaderUI-ipad.build/Debug-iphoneos/QQReaderUI.build/Objects-normal/arm64/XXXX2.o
[ 3] /Users/lingyun/Library/Developer/Xcode/DerivedData/QQReaderUI-ipad-akzqsuuhhnlhdigisyuqwzvuwrfy/Build/Intermediates/QQReaderUI-ipad.build/Debug-iphoneos/QQReaderUI.build/Objects-normal/arm64/XXXX3.o
[ 4] /Users/lingyun/Library/Developer/Xcode/DerivedData/QQReaderUI-ipad-akzqsuuhhnlhdigisyuqwzvuwrfy/Build/Intermediates/QQReaderUI-ipad.build/Debug-iphoneos/QQReaderUI.build/Objects-normal/arm64/XXXX4.o
...

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
2
3
4
5
Core1(xxxx1.o)  256.00M
Core2(xxxx2.o) 208.00M
Core3(xxxx3.o) 64.00M
Core4(xxxx4.o) 20.41M
...

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:

    1. Logging and analytics.
    1. Configuring the environment needed by the app.
    1. 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

    1. Avoid xib or storyboard; use code directly.
    1. In viewDidLoad and viewWillAppear, try to do less work, do it later, avoid doing it, or make it asynchronous.
    1. When the home page logic is complex, use Instruments Time Profiler to find time-consuming bottlenecks.

Coding Notes

    1. 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.
    1. 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.
    1. Be especially careful when writing startup-related business modules. Identify which logic can be delayed or lazily loaded.
    1. Do not make class and method names too long. On iOS, every class and method name stores a corresponding string value in the __cstring segment, 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.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:iOS Launch Optimization

Author:lingyun

Published:2018-01-30 21:42

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/01/30/ios-launch-optimization/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.