前言
最近在学习商学院的一些知识,有一些学习心得,在这里分享给大家。我在看一篇博客或者一些书籍的时候,都会按照下面的模式进行学习:
- 讲什么(作者需要讲了什么)
- 如何讲明白(作者通过什么样的方式讲明白自己的观点)
- 如何运用(实际应用场景)
- 拓展思考(结合自己的理解,进行发散性思考)
这样在学习的过程中有思考,有总结;更能抓住重点和提升学习效率。
eventBusIndex的性能提升
在没有使用EventBus之前,一般都是使用广播来实现组件之间的通信,但是随着EventBus的普及以及EventBusIndex和APT的结合,已经慢慢的接受了EventBus。3.0之前的版本都是通过反射,遍历类中所有的方法,然后寻找符合条件的方法,这种方式在一个类方法数量少的前提下没有什么问题,但是如果类中的方法较多,存在一定的性能影响。下面结合实际的测试结果来说明使用EventBusIndex和不使用之间的性能差别。
常规使用
EventBus的使用文档参考 官方文档
测试机型::华为 Honor 6X
测试代码一:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startTime = System.currentTimeMillis();
EventBus.getDefault().register(this);
long endTime = System.currentTimeMillis();
Log.d("event_bus","cut_time:"+String.valueOf(endTime - startTime));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void loginEvent(LoginEvent event){
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void userEvent(UserEvent event){
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
测试结果: 7毫秒(EventBus.register()方法执行消耗7毫秒)
测试代码二: 加入 60个方法
public void test1(){}
public void test2(){}
public void test3(){}
.......
public void test67(){}
public void test68(){}
public void test69(){}
测试结果: 10毫秒(EventBus.register()方法执行消耗10毫秒)
register所执行所消耗时间会随着方法的增多而增多。
使用eventBusIndex
eventBusIndex的使用方法如下:
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.mytestproject"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions {
annotationProcessorOptions {
//包名可以随意,但是建议和AndroidManifext.xml中的 package 一致
//类名也可以随便取
arguments = [eventBusIndex: 'com.example.mytestproject.TextEventBusIndex']
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//EventBus
implementation 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
注意:配置完成需要rebuild,完成可在build目标下看到生成的类。
在Application中加入全局配置,其他的使用方式不变。
EventBus.builder().addIndex(new TextEventBusIndex()).installDefaultEventBus();
按照第一次的两种方法进行测试,耗时为:2毫秒
由此可以看出不加index是加index耗时的3倍以上,虽然时间基本几毫秒级别,但是对整个比例确很大。使用index后以及结合APT,会在编译期间将相应的类以及对应的方法保存起来,这就比在运行期间通过反射获取符合条件的方法要高效得多。
总结:
- 讲了什么:讲了EventBus的index使用以及使用index的重要性
- 如何讲明白:通过代码示例index的使用以及对比使用index和不使用index所消耗的时间比例
- 拓展思考:随着Android开发者的增多,对技术的要求也越来越高,我们需要在能够优化的地方尽量优化,从而提升性能,提升体验;同时也是提升自我。