iOS如何提升性能book部分笔记

1、From technical standpoint(观点立场), performance is, strictly speaking, a very vague(模糊的) term. When someone says - this is a high performing application, we don’t really know what he is really talking about. Does it mean that the app uses less memory, does it save you money on network usage or does it allow you to work fluidly(流畅的) - the meaning and implications can be many. (低内层,网络使用节约钱,工作流利的)

2、Performance Dimensions 

(1)Menory (2)Power Consumption (3)Initialization Time(初始化时间) (4)Execution speed执行速度(5)responsiveness响应性(6)local storage(7)interoperability互操作性,互用性(8)network condition网络情形

(9)bandwidth带宽(10)data refresh数据刷新(11)multitenancy多租户技术(也就是一个app多账号)(12)Single sign on单点登录(13)security 安全性 (14) (9)crashes

3、Local Storage 

(1) Always give the end user an option to clean up local cache. 

     Any application that stores data on a server and/or has to refresh its data from an external source must plan for local storage for offline(离线的) viewing capabilities. 

Similarly, the news app should be able to show last updated news for offline(离线的) mode as well as an indicator against each news item indicating what is new vs. I have already ready read. And I do not need to be logged in if no subscription(捐献) is required. 

(2)、However, loading from local storage and syncing the data should be painless and fast. This may require not only choosing the data to be cached locally but also structure of the data, choosing from a host of(一大堆) options as well as frequency(频率) of sync and the likes. 

(3)、Any application that continues to hog(供起) local storage without a support to clean up is a bad one for me. The sad part is, most of the apps that I see in the market behave this way. What saddens me to see is that some of these apps consume storage in hundreds of megabytes(兆M). So, when I run out of space, I just delete these apps and do not reinstall them for a long time. 

(4)、If you look at Figure 1-1, over 12GB of space has been used and the user is left with only 950MB. What I am unhappy about is the Facebook app that is using over 250MB of space without an option for the user to clean it up. The only way to clean is to delete the app. On the other hand, Google+ uses only about 5MB of local storage. So far so good. But again, it also does not provide an option to clean up. 

4、interoperability互操作性

iOS provides multiple options for interoperability and sharing data across apps. UIAc tivityViewController, deeplinking, MultipeerConnectivity framework are some of the options available on iOS. 

Defining good URL structure for deeplinking is as important as writing good code to parse(解析) it. Similarly for sharing the data using share sheet. (写好深链接就如写好代码一样重要)It will be really a bad user experience if your app took a long time just to prepare data to be shared to the nearby device. (花时间给其他app或者附近的设备准备数据花时间很多,这是怀体验)

5、network condition网络情形

It is ok to present user with an indicator or an error message but not acceptable at all to wait indefinitely or crash the application. (给用户提供一个错误信息是可接受的,但是让app crash 或者无效期的等待是不可取的)

The image Figure 1-2 shows different ways in which you can convey the message to the end user(最终用户). TuneIn app shows how much of the streaming content it has been able to buffer. This tells the end user how long is the expected wait time before the music can start. Others like Moneycontrol or Bank of America apps just provide an indefinite progressbar - more common style for non-streaming apps. 

6、bandwidth带宽

People use mobile not only in WiFi but also on cellular networks - LTE, 3G, 2G. As per Wikipedia article on list of countries by Internet connection speeds1 rankings, World average bandwidth is 3.8Mbps with South Korea topping the list at 21.9Mbps while Bolivia at 1.0Mbps. 

As such optimal(最佳的) use of bandwidth is another key parameter that defines your product quality. Also keep in mind that if you have been developing applications using low bandwidth conditions, running it in high bandwidth can produce different results. 

I remember, in around 2010 I was developing an application with most of the dev team operating out of India. With bandwidths being terrible, the application’s local initiali‐ zation would happen long before initial responses from server were available and we tuned the application for those conditions. 

However, the application was focused on South Korean market and when we tested it there the results were extremely different. None of our optimizations and trade offs worked and we had to rewrite a large chunk of code that could have resulted in resource and data contention(争论).

7、data refresh数据刷新

Even  if you do not have any offline(线下的) viewing capabilities, you may still refersh periodically(定期地) with data from the server. The rate at which you refresh and the amount of data trans‐ ferred will affect overall data consumption. If the total bytes transferred is large, the user is bound to exhaust(排除) his data plan (Wifi or mobile internet). And if that value is large enough, you may have just lost a user. 

8、multitenancy多租户技术(也就是一个app多账号)

It is common for a family to share a mobile phone. For example, two kids may share same iPad for games. One may want to configure(配置) one device to check mails of everyone during vacation(假期) to minimize(小看) roaming costs(漫游费用) - true more so during international travel. Decision to support multiple simultaneous users is completely a product decision. But if you do decide to support, ensure that: 

9、Single sign on单点登录

10、security 安全性

Security is paramount(最重要的至高无上的) in a mobile app noting(注释) that several other apps are also installed(安装的) alongside(在旁边) - securing all communications(保证所有的安全沟通), securing data stored locally(保存数据于本地) and securing all data shared with other apps form key attributes of security. Encryption(加密术) is a great option but it increases the data processing time not to mention(提及) the overhead in memory consumed. So, you end up doing a tradeoff(权衡) between speed and encryption. But where is the inflection(变形) point between degraded user experience is a key factor deciding how much tradeoff(权衡) you want to do. Note that the hardware plays an important role - the optimizations and considerations that you may do on an iPhone 4 device can be very different than the ones on iPhone 5C or iPhone 5S. 

11、crashes

Applications can crash. Applications do crash. Extreme optimizations can lead to crash‐ es. Using native C code can lead to crashes. 

A high performing app will try to not only secure itself from crashes but also recover gracefully if a crash actually happens - sepcially if it was in middle of an operation when the crash actually happened. 

12、Before attempting to optimize your code, it is important to first identify that there is a real problem and then identify the root cause of the problem. Do not fall into the trap(陷阱) of “over optimization”(过度优化).

优化评测标准

13、memory

By memory I mean the RAM that an application consumes. There are three parts to the memory consumption(消耗) in an app. 

(1)stack size 栈尺寸

Each new thread in an app receives its own stack(堆) space consisting of both reserved(保留的) and initially(初始化) committed memory. The stack is freed(释放的) when the thread exits. Maximum stack size for a thread is very limited and among other things, it limits the following 

   *Maximum number of methods that can be called recursively(递归的). Each method has its own stack frame and it contributes to the overall stack size consumed. So, if you call main → method1 → method2, there are three stack frames contributing a few bytes each. Figure 2-1 shows how a thread stack looks like over time. 

    *Maximum number of variables that you can use within a method. All variables are loaded on the method stack-frame and hence(因此), contribute to the stack size con‐ sumed. 

   *Maximum number of views that you can nest in the view hierarchy. Redering(解释) a composite(复合材料) will invoke layoutSubViews and drawRect recursively(递归地) across the complete hierarchy tree. If the hierarchy is deep, it may result in an stack overflow(堆溢出)

(2)heap size 堆尺寸

*All threads of one process share the same heap(所有程序的线程分享相同的堆). Total heap size available for an app is generally much lower than the device RAM(堆的尺寸通常远低于设备的内存). For example, iPhone 5S may have 1GB RAM but the maximum heap size allocated to an app may be 512MB or even less.
Using NSString, loading images, creating or consuming JSON/XML data and using views will have maximum contribution to heap use. If your application is image heavy - as is the case with Flickr and Instagram - you will need special care on memory con‐sumption. 

*栈区(stack)— 由编译器自动分配释放 ,存放函数的参数值,局部变量的值等。其操作方式类似于数据结构的栈

*堆区(heap) — 一般由程序员分配释放, 若程序员不释放,程序结束时可能由OS回收 。注意它与数据结构中的堆是两回事,分配方式倒是类似于链表

*It is a good idea to keep your memory requirements to 100MB or less. Do not ignore didReceiveMemoryWarning signals. 

14、object longevity and leaks

The longer the objects live in memory, the higher are the chances of memory never being cleaned up(对象在内存中存活时间越长,内存能被清理的几率越大). Avoid long lived objects as much as possible. Of course, you will need references to key operations all over your code and you will not want to waste time recreating it each time. Due diligence(勤奋) must be done on their usage. (勤奋应该是在用处勤奋,不能做无效的勤奋)

(1)Another scenario is using global variables. Global variables are dreaded(畏惧的) in advanced proramming. 全局变量在高级项目是令人畏惧的,因为他不会被释放

(2)And as the object graph grows complex, the chances of memory being reclaimed(回收) grows slim(慢的,差的). One of the immediate results is more frequent memory crashes. Additionally, if there are multiple threads in the app, for example - for database and network operations, and they need synchronizations, there are chances of main thread waiting for an operation trigerred(触发) from elsewhere to complete before it can continue leading to user waiting for app to respond. 

(3)Apply three rules to determine if a variable qualifies to be global: 

1. It is not owned by another object. 

2. It is not a constant. 

3. There is exactly one in entire application, not just an applica‐ tion component. 

15、response time

It is the time to respond to a user interaction, another critical parameter whose value should be measure. For example, after the user taps on the Refresh icon, the time an app takes to start the request, start any animation and show the indicator to user should be minimized(最小化). 

16、execution time

One of the key attributes to measure is the time taken for critical algorithms in your code to execute. Measuring multiples of them along an execution path can give you good insights(洞察力) on how efficient is your code and how good are the data structures being used. 

17、network usage

Do not forget to measure network usage if your app uses it for anything. Be tempted to(会) go to rather extreme in check for the network usage even when an advertisement is shown. In general, I will check for: 

(1)Total bytes transferred 

(2)Average and peak bandwidth (平均和峰值带宽)

18、battery consumption

Battery is consumed whenever any hardware functions. Specficially, measure the battery consumption for the following: 一下几项评估电池消耗

(1)Intense(强度大的) task, for example image processing or scrolling. 

(2)Using hardware like camera, bluetooth and speaker. 

(3)Wake ups by Push Notifications and actions thereafter(通过通知唤醒).

(4)Background fetch 后台抓取数据

19、disk storage

Measure how much disk space your app consumes: 

(1)Application binary size 应用

Documents and files created or stored

Persistent cache

Local database store. 

20、backup size(备份的大小)

Detetermine(决定) what needs back up(需要什么支持) and what does not.Measure the typical backup size

21、Cashes

This is at the heart of my great apps.Apps crash -for whatever reasons.And once they crash ,it is hard .Measure crashes -what ,when and frquency(测试崩溃的频率,什么,何时,以及频率)

22、app usage

Apart from(除了) how your code behaves,keep a track of(追踪) how the user behaves - critical(至关重要的) user navigation paths and actions, and the commonly used paths and actions.This will help you triage(分类处理) issues.

23、Profiling(配置)

There are two ways to profile(配置文件) your application to measure the parameters that we dis‐cussed before - sampling and instrumentation(取样和检测). Sampling or probe(探针) based profiling - as the name says, requires sampling the state at periodic(周期的) intervals and is done generally by tools. We explore the tool (to come). Sam‐ pling gives a great picture of the app as it does not disturb(打扰) its execution. The downside(负面) of sampling is that you may not great 100% accurate details. If the sampling frequency is 10ms, we would not know what happens for the 9.999ms during probes.

24、Testability(可测试性):Make your code testable with mock data as well as real data, strive for automation(自动化) as much as possible and more importantly make it possible for key scenarios(情节) be tested in isolotion(隔离).

25、traceability(可追溯性):ability to trace where an error occurred if and when it occurs and support it enough diagnostics(诊断学) information so that issue can be fixed.

26、crash reporting

27、In this chapter we did a study of key performance indicators ,more commonly referred to as KPIs, to measure.

28、In this chapter we did a study of key performance indicators, more commonly referred to as KPIs, to measure. We looked at the concept of profiling(轮廓) and explored two broad categories of profiling techniques - sampling and instrumentation. We also looked at some code changes required to instrument our app. We played around with the instrumented app causing the events to be generated. 

Finally, we added some boilerplate(样板文件) code for classes that will help in instrumentation and logging. In the next chapter, we will explore fundamental optimizations and basic techniques for what I call as core optimizations - few topics that are independent of the underlying systems and the techniques that can be used anywhere and everywhere. 

29、Core Optimizations

iPhone and iPad are resource constrained(驱使) on memory. iOS virtual(虚拟的) memory model, not surprisingly enough, does not include swap(交换) memory. What is even more interesting is the fact that most of the developers that you will ever meet tend to either over-emphaize(过度强调) the need to optimize or under-emphasize to be cognizant of(被认识到) the memory usage. Unlike other environments like Java Virtual Machine1 or Dalvik2, iOS execution envi‐ ronment does not support garbage collection3. 

30、The memory management model is based on the concept of ownership. 

内存管理模型是基于拥有关系的概念

31、stack(栈) 和heap(堆)

http://net-informations.com/faq/net/stack-heap.htm

32、As of writing, there are dozens of(数十名) crash reporters available in the market1. With no particular bias(偏见), I will use Flurry(慌张). The only reason I choose Flurry is because I can setup crash reporting as well as instrumentation using one SDK. 

You can go to Flurry website to create an account, get an API key, download the SDK and follow basic setups for setup. (Flurry是一个crash报告工具)

33、Logging(日志记录) is an invaluable(无价的) tool to know what’s going on the app. Strictly speaking, there are only subtle(微妙的) differences between logging and instrumentation. (在loging和instrumentation有很大区别)

34、Addtionally, we also setup our HPLogger class for logging. Again, to start with, it just logs using NSLog. In future, we can get fancy by logging to a file or logging in memory and then showing up the entire log in the UI in the debug build of the app. We do, however, make use of log-level that can be set once application-wide during startup, say, from a configuration value in the main bundle. The possibilities of what we can do with the data are limitless. 

35、autolease pool blocks are Omnipresent(无所不在的)

36、Cocoa framework expects code execution within an autoreleasepool block lest(唯恐) autor release objects are not released and application starts leaking memory. 

37、要学到50页

猜你喜欢

转载自blog.csdn.net/u014544346/article/details/84591286