Q&A

1. What are the causes of tableView lag?

  • 1. The most commonly used is the reuse of cells and the registration of reuse identifiers

    If a cell is not reused, a new cell is created every time a cell is displayed on the screen

    If you have a lot of data, you accumulate a lot of cells.

    If you reuse a cell, create an ID for it. When a cell needs to be displayed, the system searches the buffer pool for a cell that can be reused. If the cell is not created again, the system searches the buffer pool for a cell that can be reused

  • 2. Avoid rearranging the cell

    Operations such as cell layout and filling are time-consuming. Generally, cell layout is completed when the cell is created

    If the cell can be placed in a custom class alone, it will be laid out at initialization

  • 3. Calculate and cache cell attributes and contents in advance

    When we create a cell’s data source method, the compiler does not create the cell first and then specify its height

    After the height is determined, the cell to be displayed is created. When scrolling, the height will be calculated every time the cell enters virtual. The height will be estimated in advance to tell the compiler, and then the compiler will create the cell after knowing the height. This is a way to waste time evaluating cells that are not displayed

  • 4. Reduce the number of controls in the cell

    Try to make the layout of cells roughly the same, different styles of cells can use different reuse identifiers, add controls at initialization,

    What doesn’t apply can be hidden

  • 5. Do not use ClearColor, no background color, and do not set opacity to 0

    Rendering takes a long time

  • 6. Use partial updates

    If only a group is updated, use the reloadSection for local updates

  • 7. Load network data, download images, use asynchronous loading, and cache

  • 8. Use addView less to dynamically add views to cells

  • 9. Load cells as required. If a cell rolls quickly, load only the cells in the range

  • 10. Don’t implement useless proxy methods. TableView only complies with two protocols

  • 11. High cache row: estimatedHeightForRow cannot exist at the same time as layoutIfNeed in HeightForRow. So my advice is: whenever the line height is fixed, write the estimated line height to reduce the number of line height calls and improve performance. Instead of writing predictive methods for dynamic line height, use a line height cache dictionary to reduce the number of calls to your code

  • 12. Don’t do extra painting. When you implement drawRect:, its rect parameter is the region to draw, and anything outside that region is not to be drawn. For example, in the above example, CGRectIntersectsRect, CGRectIntersection or CGRectContainsRect can be used to determine whether image and text need to be drawn, and then call the drawing method.

  • 13. Pre-rendered images. There is still a brief pause when a new image appears. The solution is to draw it in a Bitmap context, export it as a UIImage object, and then draw it to the screen;

  • 14. Use the right data structure to store data.

2. How to improve the smoothness of tableView?

  • In essence, the CPU and GPU work is reduced to improve performance from these two aspects.

    CPU: object creation and destruction, object property adjustment, layout calculation, text calculation and typesetting, picture format conversion and decoding, image drawing

    GPU: Texture rendering

  • Caton optimization at the CPU level

    Try to use lightweight objects, such as CALayer instead of UIView, for places that don’t handle events

    Don’t make frequent calls to UIView properties such as frame, bounds, Transform, etc., and minimize unnecessary changes

    Try to calculate the layout in advance, adjust the corresponding attributes at one time if necessary, do not modify the attributes more than once

    Autolayout consumes more CPU resources than setting the frame directly

    The image size should be exactly the same as the UIImageView size

    Control the maximum number of concurrent threads

    Try to put time-consuming operations into child threads

    Text processing (size calculation, drawing)

    Image processing (decoding, rendering)

  • Caton optimization at the GPU level

    Try to avoid the display of a large number of pictures in a short period of time, as far as possible to display a composite of multiple pictures

    The maximum texture size that GPU can process is 4096×4096. Once the texture size exceeds this size, IT will occupy CPU resources for processing, so the texture size should not exceed this size

    Minimize the number of views and levels

    Reduce transparent views (alpha<1) and set Opaque to YES for opaque views

    Try to avoid off-screen rendering

  • IOS tips for keeping the interface smooth

  1. Pre-typesetting, pre-calculation

    After receiving the data returned by the server, try to calculate the results of CoreText typesetting, the height of individual controls and the height of the whole cell in advance and store them in the attributes of the model. When needed, it can be taken directly from the model, avoiding the process of calculation.

    Use UILabel as little as possible and use CALayer instead. Avoid AutoLayout’s automatic layout technology and adopt a pure code approach

  2. Prerender, draw ahead of time

    For example, the circular icon can be processed in the background thread in advance when the network data is received, stored directly in the model data, and called directly after the main thread

    Avoid using CALayer’s Border, corner, Shadow, mask and other techniques, which trigger off-screen rendering.

3. Draw asynchronously

4. Global concurrent threads

5. Efficient asynchronous loading of images

3. From what aspects should APP startup time be optimized?

App startup times can be measured using the tools provided by Xcode. In Xcode’s Product->Scheme- >Edit Scheme->Run->Auguments, set the environment variable DYLD_PRINT_STATISTICS to YES

  • dylib loading time

    The core idea is to reduce references to dylibs

    Merge existing Dylibs (preferably less than 6)

    Using static libraries

  • rebase/binding time

    The core idea is to reduce the number of Pointers in the DATA block

    Reduce Object C metadata, reduce the number of Objc classes, reduce instance variables and functions (conflict with object-oriented design ideas)

    Reduce c++ virtual functions

    Use more Swift structures (Swift is recommended)

  • ObjC setup time

    The core idea is the same as above. Basically, this part will not be too time-consuming after the optimization of the previous stage

    initializer time

  • Use initialize instead of the load method

    Reduce the use of C/C ++ attributes ((constructor)); Methods such as dispatch_once() pthread_once() STD :once() are recommended

    Swift is recommended

    Do not call the dlopen() method during initialization, because the loading process is single-threaded and lockless. If you call dlopen, it will become multi-threaded, opening up lock consumption and possibly deadlocks

    Do not create threads during initialization

4. How to reduce the size of the APP package

There are two ways to reduce package size

  • Executable file

    Compiler optimization: Strip Linked Product, Make Strings read-only, Symbols Hidden by Default set to YES Enable C++ Exceptions, Enable objective-C Exceptions set to NO, Other C Flags add -fno-exceptions to detect unused code with AppCode: Menu bar -> Code -> Inspect Code

    Write the LLVM plug-in to detect duplicate code, uncalled code

  • Resources (pictures, audio, video, etc.)

    The optimized way can compress the resources losslessly

    Remove unused resources: github.com/tinymind/LS…

5. How to detect off-screen rendering and optimization

6. How do I detect layer blending

  • 1. The “color blended Layers” area in simulator debug indicates that the layer is blended
  • 2, Instrument- select Core Animation- select Color Blended Layers

Avoid layer blending:

- Ensure that the opaque property of the control is set to true, ensure that the backgroundColor is the same color as the parent view and is opaque - Do not set the alpha value below 1 unless otherwise required - Ensure that the UIImage has no alpha channelCopy the code

UILabel layer blending solution:

IOS8 after setting the background color is not transparent color and set label. Layer. MasksToBounds = YES let label will only render her actual size of the area, can solve a UILabel layer mixed problem

Before iOS8, you just set the background color to be opaque

Why did I set the background color and still get layer blending on iOS8?

UILabel before and after iOS8, before iOS8, UILabel used CALayer as the bottom layer, but starting with iOS8, the bottom layer of UILabel has changed to _UILabelLayer, and the drawing text has changed.

There is an extra transparent edge around the background color that clearly extends beyond the layer’s rectangular area. Setting the layer masksToBounds to YES will crop the layer along the Bounds

7. How to check for memory leaks?

There are several ways I know of so far

  • Memory Leaks

  • Alloctions

  • Analyse

  • Debug Memory Graph

  • MLeaksFinder

The leaked memory includes the following two types:

  • Laek Memory is the Memory leaked by forgetting to Release.

  • Abandon Memory is a kind of Memory that can’t be freed and is referenced in a loop.

8. How to optimize the power of APP?

  • The power consumption of the program is mainly in the following four aspects:

    CPU

    positioning

    network

    image

  • The optimization approach is mainly reflected in the following aspects:

Minimize CPU and GPU power consumption.

Use timers as little as possible.

Optimize I/O operations.

Do not write small data frequently, but accumulate a certain amount of data before writing

Large amounts of data can be read and written using Dispatch_io, which has been optimized internally in GCD.

If a large amount of data is required, use a database

  • Network optimization

Reduce compression of network data (XML -> JSON -> ProtoBuf) and recommend using ProtoBuf if possible.

If the request returns the same data, you can cache it using NSCache

Use breakpoint continuation to avoid re-downloading after a network failure.

Do not attempt to make a network request when the network is unavailable

Long network requests that provide cancelable operations

Take batch transmission. When downloading a video stream, try to download it in chunks. Ads can be downloaded multiple times

  • Optimization at the location level

If you just need to quickly determine the user’s location, it’s best to use the requestLocation method of CLLocationManager. After the completion of positioning, it will automatically make the positioning hardware power off if it is not a navigation application, try not to update the location in real time. After positioning, turn off the positioning service to reduce the positioning accuracy as far as possible, such as try not to use the highest accuracy kCLLocationAccuracyBest

Need background position, try to set up pausesLocationUpdatesAutomatically to YES, If the user is unlikely to move the system will automatically suspended position update Try not to use startMonitoringSignificantLocationChanges, priority startMonitoringForRegion:

  • Hardware detection optimization

When the user moves, shakes or tilts the device, motion events are generated, which are detected by hardware such as accelerometers, gyroscopes and magnetometers. These hardware should be turned off when testing is not required