簡體   English   中英

顯式轉換為相同類型

[英]Explicit conversion to the same type

顯式轉換為相同類型是否會影響性能,還是它們會被編譯器過濾而永遠不會到達字節碼?

例:

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

在此類上運行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

Sun將其稱為身份轉換。

-引用鏈接-

任何類型都允許從類型到相同類型的轉換。

這看似微不足道,但有兩個實際后果。 首先,始終允許表達式以所需的類型開頭,從而允許簡單陳述的規則,即如果只是瑣碎的標識轉換,則每個表達式都必須進行轉換。 其次,它意味着為清楚起見,允許程序包含冗余的強制轉換運算符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM