Optimization of Java (Android) code for performance optimization

Source: Internet
Author: User

Optimization of Java (Android) code for performance optimization

This article is the third--java (Android) code optimization for Android performance optimization. This paper mainly introduces the performance optimization methods and network optimization in Java code , including caching, asynchronous, delay, data storage, algorithm, JNI, logic and other optimization methods. (Time rush, will continue to improve ^_*)

The current performance optimization topic has been completed in the following sections:

Performance Optimization Master-performance issues and performance tuning methods

Performance optimization fourth-mobile network optimization

Performance optimization Third--java (Android) code optimization
Performance optimization second--layout optimization
Performance optimization first--Database performance optimization

Performance optimization Examples
1. Reduce Execution time
This part includes: Cache, data storage optimization, algorithm optimization, JNI, logic optimization, optimization of demand optimization methods.
(1). cache
The cache mainly includes object cache, IO cache, network cache, DB cache, the object cache can reduce the allocation of memory, the IO cache reduces the number of disk reads and writes, the network cache reduces network transmission, and the DB cache is less than the number of database accesses.
In memory, file, database, network read and write speed, memory is optimal, and the speed of the order of magnitude difference, so as far as possible will need to frequent access or access to a large consumption of data stored in the cache.

Caching is often used in Android:
A. Thread pool
B. Android image cache, Android image sdcard cache, data prefetch cache
C. Message Caching
The message before the handler.obtainmessage is reused as follows:

1 Handler. SendMessage(handler. Obtainmessage(0, object));

D. ListView Cache

E. Network Cache
The database caches HTTP response, which determines the cache expiration time based on the Cache-control domain in the HTTP header information.
F. File IO Caching
Using an input stream with a cache policy, Bufferedinputstream replaces the Inputstream,bufferedreader alternative to Reader,bufferedreader bufferedinputstream. to files, Network IO is applicable.
G. Layout cache
H. Other needs frequent access or access to a large data cache

(2). Data storage optimization
Includes the data type, the choice of the structure.
A. Data type selection
string concatenation uses StringBuilder instead of string, and StringBuilder instead of StringBuffer in the case of non-concurrency. If you have a general understanding of the length of the string, such as about 100 characters, you can specify the initial size directly from new StringBuilder (128), reducing the redistribution when space is not enough.
A 64-bit type such as a long double is slower than 32 bits, such as int
More useful for system garbage collection using SoftReference, WeakReference, and relatively normal strong applications
Final type storage is more efficient in constant area reading
Localbroadcastmanager replaces common broadcastreceiver for higher efficiency and safety

B. Data structure selection
Common data structures are selected such as:
ArrayList and LinkedList Choice, ArrayList based on index value faster, LinkedList more memory, random insert delete faster, more efficient expansion. Generally recommended ArrayList.
ArrayList, HashMap, Linkedhashmap, HashSet choice, hash series data structure query speed is better, ArrayList store ordered elements, HashMap for key-value data structure, Linkedhashmap can remember that the hashmap,hashset of the join order does not allow repeating elements.
HashMap, Weakhashmap selection, weakhashmap elements can be automatically reclaimed by the system garbage collector at the appropriate time, so it is suitable for use in memory-intensive type.
The choice of Collections.synchronizedmap and Concurrenthashmap, the Concurrenthashmap is the subdivision lock, the lock granularity is smaller, the concurrency performance is better. Collections.synchronizedmap is an object lock, it is more convenient to add function to lock control.

Android also offers some of the more powerful data types, such as Sparsearray, Sparsebooleanarray, Sparseintarray, and Pair.
The data structure of the sparse series is a special process for the case of the key int, using binary lookup and simple array storage, plus the overhead of not requiring a generic conversion, and better performance than the map. But I don't quite understand why the default capacity size is 10, is it statistical, or now memory optimization does not need to consider these things, write 16 will die, or recommend that you set the initial value according to their possible capacity.

(3). Algorithm optimization
This topic is bigger, need concrete problem concrete analysis, try not to use O (n*n) time complexity above algorithm, necessary time free space change time.
The query considers the hash and the two points, try not to recursion. Can be from the structure of the method of the algorithm or Microsoft, Google and other aspects of the test study.

(4). JNI
Most Android applications are developed in Java, requiring the Dalvik JIT compiler to run Java bytecode into cost code, while local code can be directly executed directly by Device Manager, saving intermediate steps, so execution is faster. However, it is important to note that switching from Java to local space requires overhead, while the JIT compiler can generate optimized native code, so bad native code does not necessarily perform better.
This optimization point will be followed by a separate blog introduction.

(5). Logical optimization
This is different from the algorithm, mainly to clarify the program logic, reduce unnecessary operations.

(6). Demand optimization
This will not say, for SB's demand may bring performance problems, can only be said as a qualified programmer can not just performers, to learn to say no. But do not take this interface perfunctory product Manager Oh.

2, asynchronous, using multithreading to improve TPS
Take advantage of multi-core CPUs to leverage threading to solve intensive computing, IO, and network operations.
Reference to Multithreading: Java thread pool
In Android applications due to system ANR limitations, it is possible to cause the mainline blocks until those operation to be placed in another worker thread. In a worker thread, you can interact through handler and the main thread.

3, advance or delay operation, stagger the time period to improve TPS
(1) Delay operation
Does not perform time-consuming operations on response-times-sensitive functions, such as activity, Service, broadcastreceiver life cycle, etc., and can be appropriately delay.
Delay operation in Java can use Scheduledexecutorservice, not recommended to use Timer.schedule;
In addition to supporting Scheduledexecutorservice in Android, there are some delay operations, such as
Handler.postdelayed,handler.postattime,handler.sendmessagedelayed,view.postdelayed,alarmmanager timing and so on.

(2) Advance operation
For the first invocation of a more time-consuming operation, it is time-consuming to put it into the initialization in a unified format. If you get wallpaper wallpapermanager.getdrawable ();

4. Network optimization
See performance optimization fourth-mobile network optimization

The following are some of the guidelines that the client and server sides of network optimization need to follow as much as possible:
A. Pictures must be cached, it is best to do pictures according to the model to do a picture adaptation
B. All HTTP requests must be added Httptimeout

C. Turn on gzip compression
D. API interface data is returned in JSON format instead of XML or HTML
E. Determine 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. API interface Server-side response time not exceeding 100ms
Google is doing a project to reduce the mobile page speed to 1 seconds, focusing on https://developers.google.com/speed/docs/insights/mobile

Optimization of Java (Android) code for performance optimization

Related Article

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.