In performance optimization, the most valuable attribute is FPS:Frames Per Second, which is actually the screen refresh rate. The recommended refresh rate of Apple iPhone is 60Hz, which means that the GPU refreshes the screen 60 times Per Second, and each refresh is a frame. FPS is how many frames are refreshed per second. The FPS value of a static page is 0, which is of no reference value. The FPS value is only useful when the page is animated or sliding. The FPS value reflects the smoothness of the page, and stuttering is more obvious when the page is below 45.

Layer Blending:

Each layer is a texture, and all textures are somehow stacked on top of each other. For each pixel on the screen, the GPU needs to figure out how to mix these textures to get the RGB value of the pixel.

When Sa = 0.5, the RGB value is (0.5, 0, 0). It can be seen that when two calayers that are not completely opaque are overlaid together, the GPU will do a lot of such compound operations. The more these operations are performed, the busier the GPU will be, and the performance will definitely be affected.

Formula:

R = S + D * 1 – Sa

The resulting color is the source color (top texture)+ target color (lower texture)*(1- opacity of the source color).

When Sa = 1 and R = S, the GPU will not do any compositing, but will simply copy from this layer without thinking about anything below it (because it is obscured by it), saving the GPU a considerable amount of work.

As a developer, it’s especially important to have a learning atmosphere and a networking community, and this is one of my iOS development networking groups:130 595 548, whether you are big ox or small white are welcome to enter, let us progress together, common development! (The group will provide some free study books collected by the group owner and hundreds of interview questions and answers documents for free!)

First, entry level

1. Use ARC to manage memory 2. Use reuseIdentifier in the right place 3

6. Resize the image in ImageViews. If you want to display an image from a bundle in a UIImageView, you should make sure that the image is the same size as the UIImageView. Zooming in and out of images on the fly is expensive, especially if UIImageView is nested in a UIScrollView. If the image is loaded from a remote service and you don’t have any control over the size of the image, for example, before downloading it, you can scale it once after downloading it, preferably with a Background thread, and then use the scaled image in the UIImageView.

7. Select the right Collection.

  • Arrays: an ordered set of values. Index lookup is fast, value lookup is slow, and insert/delete is slow.
  • Dictionaries: Store key-value pairs. It’s faster to look it up by keys.
  • Sets: an unordered set of values. Quick to find by value, quick to insert/delete.

8. Enable gzip compression. Apps can rely heavily on server resources, but the problem is that we’re targeting mobile devices, so you can’t count on a good network. One way to reduce documentation is to open Gzip on the server and in your app. This is especially useful for text, which has a higher compression rate. IOS already supports gzip compression by default in NSURLConnection, as do frameworks like AFNetworking based on it.

Second, the intermediate

1. Reuse and lazy load Views

  • More views means more rendering, which means more CPU and memory consumption, especially for apps that have a lot of views nested inside UIScrollView.
  • The trick here is to mimic the actions of UITableView and UICollectionView: Instead of creating all subViews at once, create them as needed, and put them in a reusable queue when they’re done. This way you only need to create your views when scrolling occurs, avoiding uneconomical memory allocation.

Cache, Cache, Cache!

  • A good rule of thumb is that the cache needs things that are not likely to change but need to be read frequently.
  • What can we cache? Some options are the response from the remote server, images, and even computed results, such as the row height of a UITableView.
  • NSCache is similar to NSDictionary, except that when the system reclaims memory, it automatically deletes its contents.

3. Weigh rendering methods. Performance depends on keeping bundles at the right size.

4. Handle memory warnings. Remove strong references for caches, image objects, and other objects that can be recreated.

Reuse large overhead objects

Some objects are slow to initialize, such as NSDateFormatter and NSCalendar. However, you will inevitably need to use them, such as parsing data from JSON or XML. To avoid the bottleneck of using these objects, you need to reuse them, either by adding properties to your class or by creating static variables.

7. Avoid reprocessing data. It is important to use the same data structure on both the server and client sides.

8. Choose the right data format. Parsing JSON is faster than XML, and JSON is usually smaller and easier to transport. JSON deserialization is easy to use since iOS5 with official built-in JSON deserialization. But XML also has XML benefits. For example, parsing XML with SAX is like parsing local files; you don’t have to wait until the entire document has been downloaded to start parsing, as you do with JSON. When you deal with very large amounts of data, you can dramatically reduce memory consumption and increase performance.

9. Set the background image correctly

  • Full screen background, add a UIImageView to the view as a child view
  • Just the background image of a small view, you’ll need to do it with UIColor’s colorWithPatternImage, which will render faster and cost less memory:

Reduce the use of Web features. For better performance you need to tweak your HTML. The first thing to do is to remove unnecessary javascript whenever possible and avoid using overly large frameworks. It would be nice to just use native JS. Load javascript that does not affect page presentation, such as user behavior statistics scripts, asynchronously whenever possible. Pay attention to the images you use and make sure they fit the size you use.

11. Shadow Path. CoreAnimation has to draw and shadow your graphics in the background before rendering, which is expensive. Using shadowPath avoids this problem. With Shadow Path, iOS doesn’t have to calculate how to render every time, it uses a pre-calculated path. The problem is that calculating the path yourself can be difficult in some views, and you need to update the shadow path every time the View’s frame changes.

Optimize the Table View

  • Use reuseIdentifier correctly to reuse cells
  • Try to make all view Opaque, including the cell itself
  • Avoid gradients, zoom, and background selection
  • Cache line height
  • If the actual content in the cell comes from the Web, use asynchronous loading and cache the request results
  • Use shadowPath to draw shadows
  • Reduce the number of subviews
  • Try not to use cellForRowAtIndexPath: if you need to use it, just use – once and then cache the result
  • Use the right data structure to store data
  • Use rowHeight, sectionFooterHeight, and sectionHeaderHeight to set fixed heights, and do not request a delegate

13. Select the correct data store options

  • What’s the problem with NSUserDefaults? While it’s nice and convenient, it only works with small data, such as simple Booleans, and beyond that you need to consider other options
  • What about structured files like XML? In general, you need to read the entire file into memory to parse, which is very uneconomical. Using SAX is another hassle.
  • NSCoding? Unfortunately, it also needs to read and write files, so it has the same problems.
  • In this scenario, SQLite or Core Data is preferable. With these techniques you can load only the objects you need with specific queries.
  • SQLite and Core Data are very similar in terms of performance. They differ in how they are used.
  • Core Data represents a Graph Model of an object, but SQLite is a DBMS.
  • Apple recommends using Core Data in general, but if you have a reason not to use it, go for the lower-level SQLite.
  • If you use SQLite, you can use the FMDB library to simplify SQLite operations so that you don’t have to spend a lot of time learning SQLite’S C API.

Senior three,

1. Accelerate startup time. It’s important to open your app quickly, especially when you’re opening it for the first time. First impressions are so important to your app. What you can do is make it do as many asynchronous tasks as possible, such as loading remote or database data and parsing data. Avoid xiBs that are too large because they are loaded on the main thread. Try to use Storyboards that don’t have this problem! Be sure to disconnect the device from Xcode to test startup speed

2. Use Autorelease Pool. NSAutoreleasePool is responsible for releasing the autoreleased objects in the block. Normally it’s automatically called by UIKit. But in some cases you need to create it manually. If you create a lot of temporary objects, you’ll find that memory will continue to decrease until the objects are released. This is because memory is only freed when UIKit runs out of autoRelease pools. The message is that you can avoid this behavior by creating temporary objects in your own @Autoreleasepool.

3. Select whether to cache images. There are two common ways to load an image from a bundle, one is imageNamed, the other is image with content file, the first one is a little bit more common.

4. Avoid date format conversions. If you’re going to use NSDateFormatter to handle a lot of date formats, be careful. As mentioned earlier, it’s a good practice to reuse NSDateFormatters anytime. If you can control the date format you work with, try to use Unix timestamps. You can easily convert from timestamp to NSDate:

    - (NSDate*)dateFromUnixTimestamp:(NSTimeInterval)timestamp {
    return[NSDate dateWithTimeIntervalSince1970:timestamp];
    }

Copy the code

This will be faster than parsing a date string in C! Note that many Web apis return timestamps in microseconds, because this format is easier to use in javascript. Remember to divide by 1000 before dateFromUnixTimestamp.

How do you optimize your code for performance?

  • Use performance analysis tools, including the static Analyze tool, and the runtime Profile tool, which can be started by using the Xcode toolbar Product->Profile.

  • For example, test application startup run Time, when clicking on the Time Profiler application to start running. You can get the distribution and percentage of time spent running the entire application. In order to ensure that data analysis is true in a unified use scenario, it is necessary to use a real computer, because the simulator runs on a Mac, and the CPU on a Mac is usually faster than that on an iOS device.

  • To prevent an app from taking up too much of the system’s resources, Apple engineers working on iOS devised a “watchdog” mechanism. The watchdog monitors application performance in different scenarios. If the running time specified for the scenario is exceeded, the watchdog forces the application to terminate. Developers will see error codes such as 0x8BadF00D in crashlog.

Optimization of the Table View

  • Use reuseIdentifier correctly to reuse cells
  • Try to make all view Opaque, including the cell itself
  • If the actual content in the cell comes from the Web, use asynchronous loading and cache the request results to reduce the number of subviews
  • Try not to use cellForRowAtIndexPath: if you need to use it, just use it once and then cache the result
  • Use rowHeight, sectionFooterHeight, and sectionHeaderHeight to set fixed heights, and do not request a delegate

UIImage loading image performance problem

  • ImagedNamed initialization

  • ImageWithContentsOfFile initialization

  • ImageNamed by default caches images in memory after loading them successfully. This method looks up an image object in the system cache with a given name and returns it. If no corresponding image object is found in the cache, the image is loaded from the specified location, the object is cached, and the image object is returned.

  • Image with Content file only loads images, not caches.

  • Load a large image and use it once, using image with Content file is best, so the CPU doesn’t need to cache to save time.

  • When using scenarios for programming, it should be differentiated according to actual application scenarios. Although UIimage is small, problems will be highlighted when using more elements.

    • Do not do time-consuming operations in viewWillAppear: viewWillAppear: call viewWillAppear before the view is displayed. For efficiency reasons, do not handle complex and time-consuming operations in the method. This method sets simple things like the view’s display properties, such as the background color, font, etc. Otherwise, it will be obvious that the view is stalling or delayed.

    • In the right place to use reuseIdentifier: table view with a tableView: cellForRowAtIndexPath: for the distribution of rows cells, its data should reuse self UITableViewCell.

    • Try to make views transparent: If you have transparent views you should set their opaque property to YES. The system renders these views in an optimal way. This simple property can be set either in IB or in code.

    • Avoid xiBs that are too large: Make it as simple as possible to configure a separate XIB for each Controller. If possible, separate the View hierarchy of a View Controller into a separate XIB. When you load a NIB that references an image or sound resource, the NIB load code writes the image and sound file to memory.

    • Do not block the main thread: Never overload the main thread. Because UIKit does all the work on the main thread, rendering, managing touch responses, responding to input, and so on, it’s all done on it, and most of the things that block the main process are your app doing I/O operations that involve reading or writing to external resources, like storage or networking. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// select a child thread to perform dispatch_async(dispatch_get_main_queue(), ^{// return to main thread update UI}); });

    • If you want to display an Image from a bundle in a UIImageView, you should make sure that the Image is the same size as the UIImageView. Zooming in and out of images on the fly is expensive.

Tell me about your experience optimizing animation performance with Instrument (don’t ask me what Instrument is)

  • Apple Instrument provides a variety of templates for developers to optimize app performance and locate problems.
  • Many companies are busy with feature and don’t have enough time to optimize, resulting in developers not being familiar with Instrument.
  • However, it actually covers a very complete system of basic theoretical knowledge of computer, including memory, disk, network, Thread, CPU and GPU *
  • Wait, follow the lead to learn, is a great wealth of knowledge.
  • Animation performance is just one template, but the key is to understand how the CPU GPU works together in the above question.

Facebook startup time optimization

1. Slim request dependencies

2.UDP startup requests are cached first

3. Queue serialization processes the start response

As a developer, it’s especially important to have a learning atmosphere and a networking community, and this is one of my iOS development networking groups:130 595 548, whether you are big ox or small white are welcome to enter, let us progress together, common development! (The group will provide some free study books collected by the group owner and hundreds of interview questions and answers documents for free!)