【问题标题】:Do GreenRobot's and Guava's EventBus use reflection?GreenRobot 和 Guava 的 EventBus 是否使用反射?
【发布时间】:2016-11-22 13:37:16
【问题描述】:

我们的 Android 应用目前使用 Otto EventBus,它使用反射。我们要避免反射的开销,但要保持灵活性。 Guava's event bus 是否使用反射? GreenRobot 的呢?

如果他们不这样做,他们会使用代码生成或类似的东西吗?

【问题讨论】:

  • GreenRobot EventBus3 使用 APT 而不是反射,afaik
  • "我们希望避免反射的开销" 您确定这实际上是您的应用程序中的问题吗?当我们(Square)在 4 年前对 Otto 生成的代码进行原型设计时,订阅者的数量必须非常可笑才能产生任何实际影响。那是在 Dalvik 时代,也是在他们修复 API 14+ 上的注释反射之前。坦率地说,像这样的 cmets 通常是优化某些实际上不是问题且没有被准确测量的东西的结果。
  • @Jake Wharton 我们没有测量它。根据经验,当我想优化性能时,我倾向于避免反射。如果您有任何数据可以分享,我很乐意改变主意。
  • 不幸的是数据已经丢失多年。我会说布局膨胀比 Otto 所做的反射多 10 到 100 倍。
  • 我们实际上是在使用 React Native 作为我们的 UI(它有自己的性能开销)。但一般来说,大部分代码在后台运行在服务上,因此这里不需要担心 UI 缓慢。

标签: java reflection event-bus otto greenrobot-eventbus


【解决方案1】:

Otto 从来没有像 GreenRobot 的 EventBus 那样功能丰富 - 例如,没有线程模式,所以它是一个很好的摆脱。而 Otto 被 RxJava 弃用了——这对许多项目来说都是大材小用(个人观点)。



但是为了减少反射的使用,GreenRobot EventBus 3.x is able to build an index in compilation time using APT而不是运行时反射。

http://greenrobot.org/eventbus/documentation/subscriber-index/


索引前提条件:请注意,只有订阅者 AND 事件类公开的 @Subscriber 方法才能被索引。此外,由于 Java 注释处理本身的技术限制,@Subscribe 注释在匿名类内部无法识别。

buildscript {
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}



apply plugin: 'com.neenbedankt.android-apt'

dependencies {
    compile 'org.greenrobot:eventbus:3.0.0'
    apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}

apt {
    arguments {
        eventBusIndex "com.example.myapp.MyEventBusIndex"
    }
}

EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
// Now the default instance uses the given index. Use it like this:
EventBus eventBus = EventBus.getDefault();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多