Performance Optimization Java (Android) Code Optimization (4)

This article is reproduced from: Trinea

This article is the third part of Android performance optimization - Java (Android) code optimization. Mainly introduces performance optimization methods and network optimization in Java code , including caching, asynchronous, delay, data storage, algorithms, JNI, logic and other optimization methods.

1. Reduce execution time.
This part includes several optimization methods: caching, data storage optimization, algorithm optimization, JNI, logic optimization, and demand optimization.
(1). Cache
cache mainly includes object cache, IO cache, network cache, and DB cache. Object cache can reduce memory allocation, IO cache reduces the number of disk reads and writes, network cache reduces network transmission, and DB cache reduces database access. frequency.
Among the read and write speeds of memory, files, databases, and networks, memory is the optimal, and the speeds vary by orders of magnitude, so try to store data that requires frequent access or that consumes a large amount of money once accessed in the cache.

 

Cache is commonly used in Android:
a.   Thread pool
b.   Android image cache , Android image Sdcard cache , data prefetch cache
c. Message cache
reuses the previous message through handler.obtainMessage, as follows:

d.  ListView cache

e.  Network caching:
The database caches the http response and determines the cache expiration time based on the Cache-Control field in the http header information.
f. File IO caching
uses an input stream with a caching strategy, BufferedInputStream replaces InputStream, BufferedReader replaces Reader, and BufferedReader replaces BufferedInputStream. It is applicable to both file and network IO.
g.  Layout cache
h. Other data caches that require frequent access or consume a large amount of data once accessed

 

(2). Data storage optimization
includes the selection of data types and data structures.
a. Data type selection:
Use StringBuilder instead of String for string splicing, and use StringBuilder instead of StringBuffer in non-concurrent situations. If you have a general understanding of the length of the string, such as about 100 characters, you can directly specify the initial size with new StringBuilder(128) to reduce re-allocation when the space is insufficient.
The processing of 64-bit types such as long double is slower than that of 32-bit types such as int.
Using SoftReference and WeakReference is more conducive to system garbage collection than normal strong applications. The
final type is stored in the constant area and is more efficient in reading.
LocalBroadcastManager replaces ordinary BroadcastReceiver, and the efficiency is the same. Security is higher

 

b. 数据结构选择
常见的数据结构选择如:
ArrayList和LinkedList的选择,ArrayList根据index取值更快,LinkedList更占内存、随机插入删除更快速、扩容效率更高。一般推荐ArrayList。
ArrayList、HashMap、LinkedHashMap、HashSet的选择,hash系列数据结构查询速度更优,ArrayList存储有序元素,HashMap为键值对数据结构,LinkedHashMap可以记住加入次序的hashMap,HashSet不允许重复元素。
HashMap、WeakHashMap选择,WeakHashMap中元素可在适当时候被系统垃圾回收器自动回收,所以适合在内存紧张型中使用。
Collections.synchronizedMap和ConcurrentHashMap的选择,ConcurrentHashMap为细分锁,锁粒度更小,并发性能更优。Collections.synchronizedMap为对象锁,自己添加函数进行锁控制更方便。

 

Android也提供了一些性能更优的数据类型,如SparseArray、SparseBooleanArray、SparseIntArray、Pair。
Sparse系列的数据结构是为key为int情况的特殊处理,采用二分查找及简单的数组存储,加上不需要泛型转换的开销,相对Map来说性能更优。不过我不太明白为啥默认的容量大小是10,是做过数据统计吗,还是说现在的内存优化不需要考虑这些东西,写16会死吗,还是建议大家根据自己可能的容量设置初始值。

 

(3). 算法优化
这个主题比较大,需要具体问题具体分析,尽量不用O(n*n)时间复杂度以上的算法,必要时候可用空间换时间。
查询考虑hash和二分,尽量不用递归。可以从结构之法 算法之道微软、Google等面试题学习。

 

(4). JNI
Android应用程序大都通过Java开发,需要Dalvik的JIT编译器将Java字节码转换成本地代码运行,而本地代码可以直接由设备管理器直接执行,节省了中间步骤,所以执行速度更快。不过需要注意从Java空间切换到本地空间需要开销,同时JIT编译器也能生成优化的本地代码,所以糟糕的本地代码不一定性能更优。
这个优化点会在后面单独用一片博客介绍。

 

(5). 逻辑优化
这个不同于算法,主要是理清程序逻辑,减少不必要的操作。

 

(6). 需求优化
这个就不说了,对于sb的需求可能带来的性能问题,只能说做为一个合格的程序员不能只是执行者,要学会说NO。不过不能拿这种接口敷衍产品经理哦。

 

2、异步,利用多线程提高TPS
充分利用多核Cpu优势,利用线程解决密集型计算、IO、网络等操作。
关于多线程可参考:Java线程池
在Android应用程序中由于系统ANR的限制,将可能造成主线程超时操作放入另外的工作线程中。在工作线程中可以通过handler和主线程交互。

 

3、提前或延迟操作,错开时间段提高TPS
(1) 延迟操作

不在Activity、Service、BroadcastReceiver的生命周期等对响应时间敏感函数中执行耗时操作,可适当delay。
Java中延迟操作可使用ScheduledExecutorService,不推荐使用Timer.schedule;
Android中除了支持ScheduledExecutorService之外,还有一些delay操作,如
handler.postDelayed,handler.postAtTime,handler.sendMessageDelayed,View.postDelayed,AlarmManager定时等。

 

(2) 提前操作
对于第一次调用较耗时操作,可统一放到初始化中,将耗时提前。如得到壁纸wallpaperManager.getDrawable();

 

4、网络优化
以下是网络优化中一些客户端和服务器端需要尽量遵守的准则:
a. 图片必须缓存,最好根据机型做图片做图片适配
b. 所有http请求必须添加httptimeout

c. 开启gzip压缩
d. api接口数据以json格式返回,而不是xml或html
e. 根据http头信息中的Cache-Control及expires域确定是否缓存请求结果。

f. Determine whether the connection requested by the network is keep-alive
g. Reduce the number of network requests, and merge requests appropriately on the server side.
h. Reduce the number of redirects
i. The server-side response time of the API interface does not exceed 100ms.
Google is working on a project to reduce the speed of mobile web pages to 1 second. We are paying attention to https://developers.google.com/speed/docs/insights/ mobile


Guess you like

Origin blog.csdn.net/skylovesky/article/details/26462985