Android Performance Tuning
The number of things that TPS (transactionper Second) processes per second is the indicator of system throughput. Response time, the time when the user action starts to the system to give the user correct feedback. Generally includes system processing time + network transmission time + presentation time
Synchronous change Asynchronous
Time-consuming operations are placed in the thread to prevent the main thread from taking up, partly to resolve the ANR, note that the thread and service are combined (to prevent the activity from being recycled after the threads are recycled) and the number of threads.
Thread pool Features:
1. Reusing existing threads, reducing the cost of object creation and extinction
2. Engraved to effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, to avoid clogging
3. Provide the functions of timing execution, regular execution, single thread, concurrency control, etc.
Four thread pools:
1. Newcachedthreadpool Create a thread pool that can be cached, if the thread pool length exceeds the processing needs, can be flexibly recycled idle threads, if not recyclable, then new threads, Pool.execute (Runnale)
2. Newfiaedthreadpool creates a fixed-line pool that controls the maximum number of concurrent threads, and the threads that are exceeded wait in the queue, and the size of the thread pool is best set based on system resources such as Runtime.getruntime (). Availableprocessors (), Pool.execute (runnable)
3. Newscheduledthreadpool create a fixed-length pool to support timed and recurring task execution
Timed execution of Pool.schedule (runnable,3, timeunit.seconds);
Regular execution of Pool.scheduledatfixedrate (runnable,1, 3, timeunit.seconds), a delay of one second after every three seconds, more secure than a timer
4. Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO,LIFO, priority)
Cache
Java object creation requires more time to allocate resources, and the more objects you create, the more frequent the GC affects the system response. It mainly uses singleton mode, cache (picture cache, thread pool, view cache, IO cache, message cache, notification bar notification cache) and other ways to reduce object creation.
Single-Case mode
The privatization constructor, which defines the static instance object and the GetInstance () method, requires the getinstance () method to use a synchronous lock synchronized (Singleton.class) Prevent multithreading at the same time to cause instance multiple instantiation, to determine whether the instantiation does not need to execute synchronized each time to obtain the object lock.
Public classsingleton{
Private static Singleton instance =null;
Private Singleton () {}
public static Singleton getinstance () {
if (instance = = null) {
Synchronized (Singleton.class) {
if (instance ==null) {
Instance = Newsingleton ();
}
}
}
}
}
Picture Cache
Imagecache
Imagesdcache
View Cache
The listview cache mechanism, which reduces the number of layout inflate by convertview or not, inflate time-consuming to reduce findviewbyid by Viewholder.
@Override
public Viewgetview (int position, View Convertview, ViewGroup parent) {
Viewholder Holder;
if (Convertview = = null) {
Convertview =inflater.inflate (R.layout.list_item, NULL);
Holder = Newviewholder ();
Convertview.settag (holder);
}else{
Holder = (viewholder) convertview.gettag ();
}
}
Private Staticclass viewholder{
Private ImageView AppIcon;
Private TextView AppName;
}
IO cache
Using an input stream with a cache policy, Bufferedinputstream replaces Inputstream,bufferedread instead of reader, BufferedReader replaces bufferedinputstream, files, Network IO is applicable.
Message caching
The message object is recycled through handler's obtainmessage, reducing the creation overhead of the Message object Hander.sendmessaage (Handler.obtainmessage (1)).
Notification Bar Cache
The download needs to constantly change the status of the notification bar progress bar, if the new notification will cause the notification bar very card, map<sting, notifiction> notificationmap = newhashmap<string, Notification> (); If Notificationmap does not exist, create a new Notification and put into map.
Other
The ability to create a base class solves the problem without a specific subclass: except that the thread that needs to set the priority is created with the new thread, the rest of the thread uses new Runnable because the subclass will have its own property creation that requires more overhead
Control maximum concurrency: Use Java's executors class to control the thread pool maximum thread concurrency through Executors.newfixedthreadpool (nthreads).
HTTP requests increase timeout, the database caches HTTP response, and the cache expiration time is determined based on the Cache-control domain in the HTTP cast message.
frequently accessed, or once access consumes a large data cache.
Layout
Use abstract layout tags (include, viewstub, merge) to remove unnecessary nesting and view nodes. Reduce unnecessary inflate and layout tuning related tools (Hierarchy Viewer and lint).
TextView Property Optimization android:ellipsize= "Marquee" the performance of the marquee is extremely consumable.
A. Abstract layout label:
<include> Layout modularity
<includelayout= "@layout/layout.xml" >
<viewstub> as with the include label to introduce the external layout, Viewstub introduced by default does not expand the layout, that is, not occupy the display will not occupy the location, commonly used as the introduction of the default is not displayed, only in special cases (such as schedule layout, network failure to display the refresh layout, A hint layout for information error).
Viewstub stub = (viewstub) Findviewbyid (r.id.network_error_layout);
Viewnetworkerrorview = Stub.inflate ();
buttonnetworksetting = (Button) Networkerrorview.findviewbyid (r.id.network_setting);
<merge> Layout top node is framelayout and does not need to set properties such as background or padding, can be replaced with a merge, a layout as a sub-layout by other layout include (the outer layer is relativelayout), Use merge as the layout node.
B. Remove unnecessary nesting and view nodes, the first time you do not need to use the node settings gone or use Viewstub, the linearlayout scale is deeper than the use of relativelayout.
C. Reduction of unnecessary inflate
Above Stub.inflate (), you can first determine whether the Networkerrorview is empty.
D. Use Surfaceview or Textureview instead of normal view,surfaceview or Textureview to improve performance by moving the drawing operation to another separate thread, the normal view drawing process is done in the main thread (UI thread), Surfaceview is outside the regular view system, so it cannot be moved, scaled, or rotated like a regular view, and Textureview is drawn not only on separate threads, but also in the same way as regular views.
E. Try to create resources for all resolutions, reduce unnecessary hardware scaling, and reduce the drawing speed of the UI.
GPU Transition Drawing
Transition drawing refers to a pixel that has been drawn multiple times.
The main reasons are:
1. Too many view overlays
2. Complex Hierarchy Overlay
3. Longer inflation
Color identification: From good to poor: blue-green-pink-red
1. Blue 1x over-drawn
2. Green 2x over-rendering
3. Light Red 3x over-drawn
4. Over 4x over-painted red
Acceptance criteria:
1. Control over-draw as 2x
2.4x over-rendering is not allowed
3. Over 3x of area beyond screen 1/4 is not allowed (light red area)
Database
Mainly includes indexes and things and optimizations for SQLite:
1. Index, speed up the retrieval of database, difficult to maintain
2. Transactions, atomic commits, modifications within the same transaction either complete or fail
3. Statement stitching using StringBuilder instead of string
4. Return fewer result sets and fewer fields on query
5. Use the static variable to remember the index of a column when building a table with less cursor.getcolumnindex.
6. Asynchronous threads, concurrency, size, network limitations, and table-level locks, without multi-threading, latency lag when data is large, use a single thread pool, perform DB operations in tasks, return results with handler and UI thread interaction.
Algorithm
Use HashMap instead of ArrayList
Use Spqrsearray instead of key int type HashMap
Hanshmap loop, requires both key and value
map<srting, string> map = newhashmap<string, string> ();
For (entry<string, string> entry:map.entrySet ()) {
Entry.getkey ();
Entry.getvalue ();
}
Traverse Key Only
For (String Key:map.keySet ()) {}
Deferred execution
For many time-consuming logic does not need to be executed immediately, it can be deferred execution;
Thread deferred execution
Scheduledexecutorservicescheduledthreadpool = Executors.newscheduledthreadpool (10);
Message delayed send
Handler.sendmessagedelayed (handler.obtainmessage (0), 1000);
Network optimization
A. Pictures must be cached, preferably according to the model to do picture adaptation
B. All HTTP requests must be added Httptimeout
C. Turn on gzip compression
D. Interface data is returned in JSON format, not XML or HTML
E. Determining if the request results are cached based on the Cache-control and expires domains in the HTTP header information
F. Determine if the connection of the network request is keep-alive
G. Reduce the number of network requests, the server side do the appropriate request consolidation
H. Reducing the number of redirects
I Interface server-side response time not exceeding 100ms
Other bitmap
The concept of memory is not freed in Java design, except for large objects in actual use. An exception to this is the bitmap in Android. The bitmap of the time will cause the memory of the Puma. The Recycle method does not have to be called, and even if a GC is called, the Java layer's bitmap object is not immediately recycled, which is a matter of manually placing an object empty.
The Recycle method is to release the pixel memory of the C layer. The memory of the C layer is still in the memory of the current process, and the memory that makes up a bitmap object is mostly a C-layer pixel array, so call bitmap manually. Recycle and manually null the Java layer reference of the bitmap object to instantly free up the memory occupied by the pixel and to reclaim the memory occupied by the bitmap object the next time the virtual machine runs.
Alarmmanager
Do not use the timer without restriction, you should selectively register according to the scene and cancel the timer in time. For example, depending on the network conditions should use SyncAdapter; After user logoff, remember to log off the timer and so on. In addition, the cycle of the timer is best controlled for more than 15 minutes, this is the official Android experience, and then frequently, the impact on the mechanical and electrical consumption will become significantly larger. About the timer mode. Wakeup the benefits of the user can be concerned about the status of timely updating, but will interrupt the machine sleep, if very frequent, will use the machine can not sleep, the power consumption significantly increased. The advantage of non-wakeup is to compare power saving, but will focus all the tasks on the user wakes up the moment of the machine to execute, causing the user to wake the machine when the lag.
WakeLock
In addition to the program like video playback which needs to be kept in the foreground even if the user does not operate for a long time, there is very little need to apply for wake lock. Also, once the program exits the foreground, remember to release it.
Broadcast
A global broadcast receiver that is statically declared through Androidmanifest.xml is a large power consumer. There may be many programs that register common events such as "Network status changes," "Phone status," and "set unlock." Then, when these events occur, multiple process creation is triggered, and frequent GC, and the lag is coming. So try to use dynamic registration as much as possible. In addition, "Network status change" can use the SyncAdapter provided by Android to achieve low-cost monitoring.
Receiver's process configuration also has some tricks. If receiver needs to wake up the UI process, configure it and the UI into a process and configure it and the background service to a process if it needs to wake up the backend service. You can reduce the overhead of the system creation process.
Background services
Having a background service as a single process can greatly reduce the memory pressure of the UI process. If you put them in a process, as long as any one of them does not complete the task, both of them will remain in memory.
Long connections
Long connections mean that you need to maintain network connectivity, periodic heartbeat data transfers, devices that cannot hibernate, and use caution.
Other
64-bit type long, double processing is slower than 32-bit int
Final type storage is more efficient in constant area reading
Localbroadcastmanager replaces common broadcastreceiver for higher efficiency and safety
Android_ Performance Tuning