@NonNull 和@Nullable 注释 - 它会影响 Android 中的性能吗?

@NonNull and @Nullable annotations - Does it effect the performance in Android?

@NonNull@Nullable 注释在运行时会影响 Android 中的性能吗?我的意思是他们的目的只是为了支持 LINT 和其他工具来检测可能的错误,所以他们 probably/hopefully 在编译过程中将被忽略。你有任何资料可以证明这一点吗?

@NonNullNullable 注释用 CLASS retention policy 声明。它们出现在编译的字节码中,但可以在 运行 时间被 VM 忽略。

如果您担心性能问题,运行 可以进行一个实验,看看它是否对您来说是个问题。我假设 class-保留注释不会增加任何显着的开销。

(如果保留策略是 运行 时间 并且 注释是在 运行 时间通过反射查询的, 然后 会出现性能问题,尤其是在 past 中。)

作为一个小实验,我在 Android 应用程序中创建了以下方法:

private void test(@NonNull Object o) {
    o.toString();
}

编译项目,'un-compiled' 它与 ApkTool and took a look at the smali 文件:

.method private test(Ljava/lang/Object;)V
    .locals 0
    .param p1, "o"    # Ljava/lang/Object;
        .annotation build Landroid/support/annotation/NonNull;
        .end annotation
    .end param

    .prologue
    .line 22
    invoke-virtual {p1}, Ljava/lang/Object;->toString()Ljava/lang/String;

    .line 23
    return-void
.end method

所以 Nonnull 注解实际上并没有在编译时从代码中移除。

虽然我可以关闭 Android studio 中的检查,使用 null 作为参数调用测试方法并编译应用程序。然后,它当然会在 o.toString() 处以 NullPointerExeption 崩溃,但是没有任何提示表明 VM 实际上在运行时使用注释来检查参数。正是 laalto 在他的回答中所说的。

我确实想知道 VM 是否能够这样做并在使用 null 参数调用该方法时抛出异常。