IOS App Performance Optimization

Source: Internet
Author: User

The iphone app has always been known for its smooth operating experience, but since developers have focused more on development features than on performance, this may involve objective-c,c++ and Lua, which are relatively complex to optimize. resulting in applications such as touch and other lower end of the product, light from the start to the page to take nearly a minute, the switch between the page is not that very smooth feeling, memory is also high, the impact of the user experience of the application, so it is necessary to do some optimization, Let's take a look at some of the things I've learned during the optimization process:

1 instruments

?? In the performance analysis on iOS, first consider the use of instruments this tool to analyze the problem where, do not imagine, otherwise you may spend 1% of the problem, and finally found that nothing is optimized, such as to see which parts of the program is the most time-consuming, you can use Profiler, to see if the memory is leaking, you can use leaks and so on. There is a lot of information on instruments online, as a qualified iOS developer, it is necessary to be familiar with this tool.

2 do not block the main thread

?? The Uikit operation on iOS is always on the main thread, so if the main thread is blocked, your UI may not respond to events in a timely manner, giving a feeling of lag. Most of the blocking main thread is the main thread to do IO operations, such as file read and write, including database, image, JSON text or log logs, and so on, as far as possible to put these operations on child threads (if the database has more operations, remember to use transactions to deal with, performance difference is quite large), or set up a corresponding dispatch queue in the background to do this, such as a low-level serial queue to be responsible for log file records and so on. In the program if your code logic is written according to the logic of synchronization, try to modify the logic code it ...

3 using the Cache

?? In general, in order to improve the user experience, will be used in the application of the cache, for example, the image resources can use sdwebimage this open source Library, the implementation of a picture cache function. Refer to the Sdwebimage code itself can also implement the cache function:


Cache simple

The business layer obtains the corresponding resources according to the resource URL to the ResourceManager, ResourceManager first will go to memorycache this side to obtain the resources, MemoryCache may use nscache realization, Because Nscache is thread-safe first, it releases the corresponding memory when the memory warning is received, and if MemoryCache does not have the corresponding resources to disk, then the disk does not have the words to go to the Internet to obtain, Get the words will be updated to MemoryCache and disk, specifically to refer to the Sdwebimage implementation details.

4 Reducing the task during program startup

When the user clicks on the app's icon, the program should go to the main page as soon as possible, to minimize the user's waiting time, such as our application in the launch of the 3d model to do the rendering operation, after the completion of the first page to show, but in fact, we can first go to the homepage, The task of rendering 3d is placed on a child thread to complete, shortening the time that the user needs to wait.


3d5 using the appropriate data structure

Depending on the business scenario to choose the right data structure, you may not see the difference in the amount of data, but if you store a large amount of data and complex data structure, this may affect your program performance. The more commonly used data structure is the array, but we know that its lookup complexity is O (n), so if you need to quickly find an element, you can use map. You can refer to the Apple collections programming Topics.

6 Memory

The arc used in general development does not require developers to focus on the creation and release of memory, but if you are using MRC and are mixed with other languages (such as C + + and LUA), how to ensure that memory is properly released is something you need to consider. Sometimes some memory leaks instruments may not be accurate analysis, then you need to troubleshoot, you can use the method swizzling to help us troubleshoot memory leaks, to ensure the correct operation of the program.

7 Lazy Load View

Do not nest too many view in the cell, this will affect the smoothness of the slide, and more view also need to spend more CPU and memory. If the slide is not smooth due to too much view, do not create all of the view at once, and put some of the view into the cell when it needs to be displayed.

8 LUA optimization

Because the business of the project is and some of the framework is implemented in Lua, so also by the way, the problem with Lua. Lua claims to be the fastest scripting language, there is no general performance problem, if the LUA code to optimize, there are a lot of this optimization point of attention, this time I mainly say a possible impact on the performance of the point---lua garbage collection. Garbage collection is a time-consuming operation, if the garbage collection operation is too frequent will inevitably affect the operation of the program, such as the ipod in the use of Lua_cjson parsing a 4.7M JSON file is spent 3.43s time, and later found to be related to garbage collection. General memory usage is moderate, can not go to him, let Lua incremental mode to deal with it, normal situation this will work better; If you want to control the GC's operation, you can set the GC parameters, these parameters may have a certain relationship with the project, You can experiment with the best value.

//gc 的参数设置,根据情况取最优值collectgarbage("setpause", 150)collectgarbage("setstepmul", 200)

?? The above is a summary of some of my records in the optimization process

About iOS graphics performance this piece of optimization

This time, let's talk about the things that slide in the iOS app. iOS in order to improve the smoothness of the slide, deliberately when sliding the Runloop mode to the Uitrackingrunloopmode, in the process of focusing on the slide-related work, which is the reason why the nstimer in the sliding process is not working, Because two of them are not under the same mode. However, we may often encounter a situation where the slippage is not smooth, for example, in a project where the sliding tableview is not very smooth, feeling a little uncomfortable, even the best performance in the test 5s (touch and other feelings more intuitive).


TableView Slide is not smooth


?? How to deal with this situation, the analysis of image animation performance is mainly used in the core animation this component, the first simple introduction of some of the frequently used options:

    • Color Blended Layers
      The layer labeled blending is red, the opaque layer is green, and usually we want the more green areas to be as good as possible.
    • Color Hits Green and Misses Red
      If we set Viewlayer's shouldrasterize to Yes, the layers that were successfully cached will be labeled green and vice versa, and the following will be described in detail below.
    • Color copied Images
      Mark images that were copied by the core animation. This is mainly because the color format of the image can not be processed directly by the GPU, need to do the conversion on the CPU side, if the main line to do this operation on the performance will have a certain impact.
    • Color misaligned Images
      The scaled picture is labeled yellow, and pixel misalignment is marked in purple.
    • Color offscreen-rendered Yellow
      Indicates which layers need to be rendered off-screen (Offscreen-render).

After a brief introduction to some of the core animation, we look back to see what issues affect the performance of the graph, which is excerpted from WWDC2014 (advanced graphics and animations for IOS Apps, Some of the above sharing is very technical)


Performance Investigation Mindset.png


When you run into performance problems, you can think about:

是否受到CPU或者GPU的限制?是否有不必要的CPU渲染?是否有太多的离屏渲染操作?是否有太多的图层混合操作?是否有奇怪的图片格式或者尺寸?是否涉及到昂贵的view或者效果?view的层次结构是否合理?

So what are some of the things you should start thinking about? Often when graphics performance problems occur, such as the list slippage is not smooth, animation, and so on, mostly due to offscreen Rendering (off-screen rendering) or blending, because this is involved in every frame of animation.

Offscreen-render

What is Offscreen-render? Offscreen-render involved more content, there is offscreen-render that there is onscreen render,onscreen render refers to the GPU in the current screen buffer for display rendering, Conversely Offscreen-render is not in the current screen buffer, but in another buffer to render, Offscreen-render has two forms:

Offscreen-render of the CPU

Use the CPU to complete rendering manipulation, usually when you use:

    • DrawRect (do not write an empty DrawRect method in a subclass if you do not have a custom-drawn task, because if you implement this method, the view will be assigned a homestay map with pixel dimensions equal to the view size multiplied by the value of Contentsscale, resulting in a waste of resources)
    • Using the core Graphics
      The above two cases use the CPU off-screen rendering, first allocate a piece of memory, and then render operation to generate a copy of the bitmap bitmap, the entire rendering process will be synchronized in your app, and then send the bitmap package to a separate process in iOS--render server, Ideally, render server gives the content to the GPU to display directly on the screen.
Offscreen-render of the GPU

Using the GPU to create a new buffer outside the current screen buffer to draw, usually occurs:

    • Set Cornerradius, masks, Shadows,edge antialiasing, etc.
    • Set layer.shouldrasterize = YES

Rendering process


What effect does Offscreen-render have on performance? Generally speaking, off-screen rendering refers to the GPU this block (of course, the CPU will also have an impact, also need to consume a certain amount of resources), such as modifying the layer's shadow or rounded corners, the GPU needs to do additional rendering operations. The GPU is usually very fast when rendering, but when it comes to offscreen-render, it can be a bit different, because there is a new buffer to be added to render, Then the process of drawing to the current screen needs to do onscreen and offscreen context of the switch, the process of consumption will be more expensive, involving OpenGL pipeline and barrier, and offscreen-render in every frame will be involved, Therefore, improper handling will certainly have a certain impact on performance, so you can minimize the offscreen-render layer, and see which layers require off-screen rendering can be detected with the instruments Core animation tool, Color The offscreen-rendered yellow option marks the corresponding layer as yellow.

Blending

If the top view is opaque, it is possible to use the corresponding color of the view directly, but if the view is transparent, it is necessary to calculate the color value of the pixel, the more transparent the view, the greater the calculation, and therefore the performance of the graph will have a certain impact, So you can also minimize the number of transparent layers.

Demo

The following is a simple demo of the optimization process, this demo is related to the problem is encountered in the actual project, that is, the top of the list of slides in the picture is not smooth---by the shadow and the fillet caused by Offscreen-render.
The entire page is a simple tableview, where the avatar is rounded, a label has a shadow effect, and when sliding on the ipod the frame rate is only poor 28FPS.


Color offscreen-rendered Yellow
28fps.png


Where the yellow area is the off-screen rendering, which is a layer with rounded corners and shadows.

Shadowpath

You can set the shadow effect of a label by:

    cell.sign.layer.shadowOffset = CGSizeMake(0, 2);    cell.sign.layer.shadowOpacity = 0.5; cell.sign.layer.shadowColor = [UIColor blackColor].CGColor;

But you can see that this will lead to off-screen rendering, a simple way to not need off-screen rendering is to make the path of the shadow, that is, set the Shadowpath property of the layer, there is no yellow in the place where the shadows are found by instruments, and the frame rate is increased to 40FPS:

cell.sign.layer.shadowPath = [UIBezierPath  bezierPathWithRect:cell.sign.bounds].CGPath;

Set Shadowpath to eliminate off-screen rendering. pngrasterize

For a similar performance problem with rounded corners, the simplest thing to do is not to use rounded corners in the list, and if you want to use rounded corners, one of the quickest ways to improve performance is to set the layer's shouldrasterize to Yes:

    cell.layer.shouldRasterize = YES;    cell.layer.rasterizationScale = [UIScreen mainScreen].scale;

Although the rasterize layer also causes off-screen rendering, as shown, the entire cell is labeled yellow:


Shouldrasterize.png

After the layer is set Shouldrasterize=yes, the rasterized layers are saved as bitmaps and cached, and the effects such as fillets or shadows are stored directly in the bitmap, and when they need to be rendered to the screen, only the corresponding bitmap is displayed in the cache. Speeds up the entire rendering process. You can see if the layer is cached by ticking the color Hits green and Misses red option in instruments core animation, and if the layer is shown as green it is already cached, that is, the contents of this buffer are reused. Instead of recreating the buffer, it is marked in red. If you can see the settings shouldrasterize, the cell is marked green, if the sliding process is found to be red proof that there is a problem:


Cached.png


And look at the frame rate now sliding:


After optimization. png


It can be found that the performance of scrolling is greatly improved, and rasterization is significantly improved for those layers that have many sub-view nested together, view hierarchies, or complex effects, because the content is cached in the bitmap. But there are some things to be aware of when using rasterization:

    • For layers with basic content
      The content of the fake layer often changes, such as in the cell is involved in animation and so on, then the cached content is invalid, the GPU needs to recreate the buffer, resulting in off-screen rendering, which involves OpenGL context switch, but reduce performance.
    • Don't overdo it.
      The size of the buffer is set to 2.5 times times the size of the screen, and if excessive use also results in a lot of off-screen rendering.
    • If the cached content is more than 100ms unused, it will be recycled.
Tips
  • For fillets, you can use an intermediate circular transparent diagram to cover the top, although this introduces blending operations, but in most cases performance is better than off-screen rendering.
  • Make your view hierarchy flatter, because OpenGL may need to stop to synthesize the two into a buffer and then render it when it renders a layer with a sub-layer layer. (When the OpenGL renderer goes to draw each layer, it may has to stop for some subhierarchies and composite them into a s Ingle Buffer).
  • Delay Loading Pictures
    Sometimes in the side of the scrolling edge of the picture may have some impact, so you can scroll when the ImageView do not perform setimage operation, scrolling stopped when the picture is loaded, As the Nsrunloop is in Uitrackingrunloopmode mode when scrolling, you can use the following method to put the settings picture in Nsdefaultrunloopmode mode:
    UIImage *downloadedImage = ...;  [self.avatarImageView performSelector:@selector(setImage:)                             withObject:downloadedImage                             afterDelay:0                                inModes:@[NSDefaultRunLoopMode]];
  • Limit optimization mode of picture loading: Fastimagecache

IOS App performance optimization (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.