Kotlin在简单条件下使用

时间:2017-10-24 12:56:47

标签: kotlin bytecode

我个人喜欢when语法,因为它会使识别更加清晰。但是我担心这样做可能会引入“惩罚”。

我不是字节码专家,但我可以看到,对于相同的'逻辑',when子句需要更多的字节码操作。

具有3种不同Kotlin功能的简单文件

package com.whatever

fun method1(): String {
  return if (BuildConfig.DEBUG) "something" else "else"
}

fun method2(): String {
  return if (BuildConfig.DEBUG) {
    "something"
  } else {
    "else"
  }
}

fun method3(): String {
  return when (BuildConfig.DEBUG) {
    true -> "something"
    else -> "else"
  }
}

生成的字节码

  // access flags 0x19
  public final static method1()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 4 L0
    GETSTATIC com/whatever/BuildConfig.DEBUG : Z
    IFEQ L1
    LDC "something"
    GOTO L2
   L1
    LDC "else"
   L2
    ARETURN
   L3
    MAXSTACK = 1
    MAXLOCALS = 0

  // access flags 0x19
  public final static method2()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 8 L0
    GETSTATIC com/whatever/BuildConfig.DEBUG : Z
    IFEQ L1
   L2
    LINENUMBER 9 L2
    LDC "something"
   L3
    GOTO L4
   L1
    LINENUMBER 11 L1
    LDC "else"
   L5
    LINENUMBER 8 L5
   L4
    ARETURN
   L6
    MAXSTACK = 1
    MAXLOCALS = 0

  // access flags 0x19
  public final static method3()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 16 L0
    GETSTATIC com/whatever/BuildConfig.DEBUG : Z
    ISTORE 0
   L1
    LINENUMBER 17 L1
    ILOAD 0
    ICONST_1
    IF_ICMPNE L2
   L3
    LDC "something"
    GOTO L4
   L2
    LINENUMBER 18 L2
    LDC "else"
   L5
    LINENUMBER 16 L5
   L4
    ARETURN
   L6
    MAXSTACK = 2
    MAXLOCALS = 1

有人可以指出这笔费用有多重要吗?为了简单的操作,我们应该试图远离这种模式吗?

由于

1 个答案:

答案 0 :(得分:9)

这里唯一的区别是在method3BuildConfig.DEBUG值首先存储在局部变量中。将字节码反编译为Java时,您会看到以下内容:

   @NotNull
   public static final String method2() {
      return BuildConfig.DEBUG?"something":"else";
   }

   @NotNull
   public static final String method3() {
      boolean var0 = BuildConfig.DEBUG;
      return var0?"something":"else";
   }

这可以忽略不计。

如果我们扩展if/else子句,我们可以构建以下内容:

fun method4(a: Int): String {
    if (a == 1) {
        return "1"
    } else if (a == 2) {
        return "2"
    } else if (a == 3) {
        return "3"
    } else {
        return "4"
    }
}

fun method5(a: Int): String {
    when (a) {
        1 -> return "1"
        2 -> return "2"
        3 -> return "3"
        else -> return "4"
    }
}

反编译的字节码是:

@NotNull
public static final String method4(int a) {
  return a == 1?"1":(a == 2?"2":(a == 3?"3":"4"));
}

@NotNull
public static final String method5(int a) {
  switch(a) {
  case 1:
     return "1";
  case 2:
     return "2";
  case 3:
     return "3";
  default:
     return "4";
  }
}

因此,简单的when语句归结为Java中的switch语句。有关这两者之间的比较,请参阅'Why switch is faster than if'

相关问题