显式转换为相同类型

时间:2012-01-06 09:22:44

标签: java performance

对同一类型的显式转换是否会影响性能,还是由编译器过滤掉它们并且永远不会到达字节代码?

示例:

int x = 3;
int y = (int) x;

2 个答案:

答案 0 :(得分:3)

在这个类上运行javap -c:

public class SameTypeCastsDemo {

    public static void withoutCasts() {
        int x = 2;
        int y = x;
        System.out.println(y);
    }

    public static void withCast() {
        int x = 2;
        int y = (int) x;
        System.out.println(y);
    }

}

表明字节码看起来相同:

public static void withoutCasts();
  Code:
   0:   iconst_2
   1:   istore_0
   2:   iload_0
   3:   istore_1
   4:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   iload_1
   8:   invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   11:  return

public static void withCast();
  Code:
   0:   iconst_2
   1:   istore_0
   2:   iload_0
   3:   istore_1
   4:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   7:   iload_1
   8:   invokevirtual   #3; //Method java/io/PrintStream.println:(I)V
   11:  return

更新:使用非基本对象引用:

public class SameTypeCastsDemo {
    Integer x;
    Integer y;

    public SameTypeCastsDemo(Integer x, Integer y) {
        this.x = x;
        this.y = y;
    }

    public void print() {
        System.out.println(y);
    }

    public static void withoutCasts() {
        SameTypeCastsDemo x = new SameTypeCastsDemo(2, 3);
        SameTypeCastsDemo y = x;
        y.print();
    }

    public static void withCast() {
        SameTypeCastsDemo x = new SameTypeCastsDemo(2, 3);
        SameTypeCastsDemo y = (SameTypeCastsDemo) x;
        y.print();
    }

}

javap -c SameTypeCastsDemo:

public static void withoutCasts();
  Code:
   0:   new #6; //class SameTypeCastsDemo
   3:   dup
   4:   iconst_2
   5:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   8:   iconst_3
   9:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   12:  invokespecial   #8; //Method "<init>":(Ljava/lang/Integer;Ljava/lang/Integer;)V
   15:  astore_0
   16:  aload_0
   17:  astore_1
   18:  aload_1
   19:  invokevirtual   #9; //Method print:()V
   22:  return

public static void withCast();
  Code:
   0:   new #6; //class SameTypeCastsDemo
   3:   dup
   4:   iconst_2
   5:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   8:   iconst_3
   9:   invokestatic    #7; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   12:  invokespecial   #8; //Method "<init>":(Ljava/lang/Integer;Ljava/lang/Integer;)V
   15:  astore_0
   16:  aload_0
   17:  astore_1
   18:  aload_1
   19:  invokevirtual   #9; //Method print:()V
   22:  return

答案 1 :(得分:1)

Sun称之为identity conversion.

- 引用链接 -

  

任何类型都允许从类型转换为相同类型。

     

这看似微不足道,但它有两个实际后果。第一,   表达式始终允许具有所需的类型   开头,从而允许简单陈述每个表达式的规则   如果只是一个微不足道的身份转换,则会受到转换。   其次,它意味着允许程序包含   为了清晰起见,冗余的转换操作符。