(点击上方的 蓝色文字 ,可快速关注我们)
本文主要分享自己在appstore项目中的性能调优点,包括 同步改异步、缓存、Layout优化、数据库优化、算法优化、延迟执行 等。
一、性能瓶颈点
整个页面主要由6个Page的ViewPager,每个Page为一个GridView,GridView一屏大概显示4*4的item信息(本文最后有附图)。由于网络数据获取较多且随时需要保持页面内app下载进度及状态,所以出现以下性能问题
a. ViewPager左右滑动明显卡顿
b. GridView上下滚动明显卡顿
c. 其他Activity返回ViewPager Activity较慢
d. 网络获取到展现速度较慢
二、性能调试及定位
主要使用 Traceview 、mon key、mon key runner调试, traceview类似java web调优的visualvm ,使用方法如下:
在需要调优的activity onCreate函数中添加
?
1 |
android.os.debug.startMethodTracing(
"Entertainment"
);
|
onDestrory函数中添加
?
1 |
android.os.debug.stopMethodTracing(); |
程序退出后会在sd卡根目录下生成Entertainment.trace这个文件,cmd到android sdk的tools目录下运行traceview.bat Entertainment.trace即可,截图如下
从中可以看出各个函数的调用时间、调用次数、平均调用时间、时间占用百分比等从而定位到耗时的操作。
三、性能调优点
主要包括同步改异步、缓存、Layout优化、数据库优化、算法优化、延迟执行。
1. 同步改异步
这个就不用多讲了,耗时操作放在子线程中执行防止占用主线程,一定程度上解决anr。
但 需要注意线程和service结合(防止activity被回收后线程也被回收) 以及线程的数量(后面优化介绍)
PS:请使用java的线程池(后面介绍),少使用AsyncTask,因为AsyncTask存在性能问题。
2. 缓存
java的对象创建需要分配资源较耗费时间,加上创建的对象越多会造成越频繁的gc影响系统响应。主要使用 单例模式、缓存(图片缓存、线程池、View缓存、IO缓存、消息缓存、通知栏notification缓存)及其他方式 减少对象创建。
(1). 单例模式
对于创建开销较大的类可使用此方法,保证全局一个实例,在程序运行过程中该类不会因新建额外对象产生开销。示例代码如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
单例模式:
class
Singleton {
private
static
Singleton instance =
null
;
private
Singleton() {
}
public
static
Singleton getInstance() {
if
(instance ==
null
) {
instance =
new
Singleton();
}
return
instance;
}
} |
(2). 缓存
程序中用到了 图片缓存、线程池、View缓存、IO缓存、消息缓存、通知栏notification缓存 等。
a. 图片缓存: 见 ImageCache 和 ImageSdCache
b. 线程池: 使用Java的Executors类,通过newCachedThreadPool、newFixedThreadPool、newSingleThreadExecutor、newScheduledThreadPool提供四种不同类型的线程池
c. View缓存:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
listView的getView缓存: @Override
public
View getView(
int
position, View convertView, ViewGroup parent) {
ViewHolder holder;
if
(convertView ==
null
) {
convertView = inflater.inflate(R.layout.type_item,
null
);
holder =
new
ViewHolder();
holder.imageView = (ImageView)convertView.findViewById(R.id.app_icon);
holder.textView = (TextView)convertView.findViewById(R.id.app_name);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.imageView.setImageResource(R.drawable.index_default_image);
holder.textView.setText(
""
);
return
convertView;
}
/** * ViewHolder */
static
class
ViewHolder {
ImageView imageView;
TextView textView;
} |
通过convertView是否为null减少layout inflate次数,通过静态的ViewHolder减少findViewById的次数,这两个函数尤其是inflate是相当费时间的
d. IO缓存:
使用具有缓存策略的输入流,BufferedInputStream替代InputStream,BufferedReader替代Reader,BufferedReader替代BufferedInputStream.对文件、网络IO皆适用。
e. 消息缓存: 通过Handler的obtainMessage回收就的Message对象,减少Message对象的创建开销
handler.sendMessage(handler.obtainMessage(1));
下载中需要不断改变通知栏进度条状态,如果不断新建Notification会导致通知栏很卡。这里我们可以使用最简单的缓存
Map<String, Notification> notificationMap = new HashMap<String, Notification>();如果notificationMap中不存在,则新建notification并且put into map.
(3). 其他
能创建基类解决问题就不用具体子类:除需要设置优先级的线程使用new Thread创建外,其余线程创建使用new Runnable。因为子类会有自己的属性创建需要更多开销。
控制最大并发数量:使用Java的Executors类,通过Executors.newFixedThreadPool(nThreads)控制线程池最大线程并发
对于http请求增加timeout
3. Layout优化
性能优化相关的一些标签 <viewStub/>,<merge/>和<include/> 。
TextView属性优化:TextView的android:ellipsize=”marquee”跑马灯效果极耗性能,具体原因还在深入源码中
对于layout中的布局实际效果可使用 hierarchyviewer 查看
对于layout中多余的view以及不正确的标签可使用 android lint 查看
4. 数据库优化
主要包括sql优化、建立索引、使用事务、读写表区分
(1). sql优化
(2). 建立索引
使用CREATE INDEX mycolumn_index ON mytable (myclumn)语句在SQLiteOpenHelper子类的onCreate或onUpgrade函数创建索引,索引创建后对大数据量的查询性能提升效果较明显
(3). 使用事务
事务不仅能保证批量操作一起完成或回滚,而且在大量插入、更新、查询时减少程序和表的交互从而提高性能
?
1 2 3 4 5 6 7 8 9 10 11 12 |
事务示例: SQLiteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction();
try
{
// add to do
db.setTransactionSuccessful();
}
catch
(Exception e) {
Log.e(TAG, e.toString());
}
finally
{
db.endTransaction();
} |
(4). 读写表区分
对于查询操作使用dbHelper.getReadableDatabase();读表代替写表。因为sqlite是表级锁,所以修改和插入等写操作的性能较差。
5. 算法优化
这个就是个博大精深的话题了,只介绍本应用中使用的。
使用hashMap代替arrayList,时间复杂度降低一个数量级
6. 延迟执行
对于很多耗时逻辑没必要立即执行,这时候我们可以将其延迟执行。
线程延迟执行ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);
消息延迟发送handler.sendMessageDelayed(handler.obtainMessage(0), 1000);
四、本程序性能调优结果
1. ViewPager左右滑动明显卡顿
2. GridView上下滚动明显卡顿
(1). 去掉TextView的android:ellipsize=”marquee”
(2). 修改图片缓存的最大线程数,增加http timeout
(3). 修改设置app是否已安装的状态,具体代码修改如下:
?
1 2 3 4 5 6 7 |
List<PackageInfo> installedPackageList = getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES); List<App> installedAppList = function(installedAppList)
for
(App app : appList) {
for
(App installedApp : installedAppList) {
}
} |
修改为
?
1 2 3 4 5 6 7 8 |
for
(App app : appList) {
Pair<Integer, String> versionInfo = INSTALLED_APP_MAP.get(app.getPackageName());
if
(versionInfo !=
null
) {
}
else
{
}
} |
从每次获取List<PackageInfo> installedAppList = getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES); 修改为只在有应用安装或卸载广播时获取应用列表,并且用hashMap代替installedAppList减少查询时间。
将平均执行时间从201ms降低到1ms。
3. 其他Activity返回ViewPager Activity较慢
定位:在on Start函数
解决:使用延迟策略,具体代码修改如下:
?
1 2 3 4 5 |
<span style="font-size: 14px;">@Override</span> <span style="font-size: 14px;">}</span> |
改为
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public
void
on
Start() {
super
.on
Start();
// delay send message
handler.sendMessageDelayed(handler.obtainMessage(MessageConstants.WHAT_NOTIFY_DATA_CHANGED),
100
);
}
private
class
MyHandler
extends
Handler {
@Override
public
void
handleMessage(Message msg) {
super
.handleMessage(msg);
switch
(msg.what) {
case
MessageConstants.WHAT_NOTIFY_DATA_CHANGED:
if
(appUpdateListAdapter !=
null
) {
appUpdateListAdapter.notifyDataSetChanged();
}
break
;
}
}
} |
4. 网络获取到展现速度较慢
定位:在HttpURLConnection.getInputStream()之后的处理
解决:使用BufferedReader替代BufferedInputStream获取时间从100ms降低到3ms,具体代码修改如下:
?
1 2 3 4 5 |
HttpURLConnection con = (HttpURLConnection)url.openConnection(); InputStream input = con.getInputStream();
while
(input.read(buffer,
0
,
1024
) != -
1
) {
} |
改为
?
1 2 3 4 5 6 |
HttpURLConnection con = (HttpURLConnection)url.openConnection();
BufferedReader input =
new
BufferedReader(
new
InputStreamReader(con.getInputStream()));
String s;
while
((s = input.readLine()) !=
null
) {
} |
欢迎加入Java和Android大牛频道群,共同交流和学习!
长按下方的二维码即可快速进群!!!