java short,integer,long performance

前端 未结 6 681
我在风中等你
我在风中等你 2021-01-01 23:27

I read that JVM stores internally short, integer and long as 4 bytes. I read it from an article from the year 2000, so I don\'t know how true it is now.

For the newe

6条回答
  •  孤街浪徒
    2021-01-01 23:55

    Integer types are stored in many bytes, depending on the exact type :

    • byte on 8 bits
    • short on 16 bits, signed
    • int on 32 bits, signed
    • long on 64 bits, signed

    See the spec here.

    As for performance, it depends on what you're doing with them. For example, if you're assigning a literal value to a byte or short, they will be upscaled to int because literal values are considered as ints by default.

    byte b = 10;  // upscaled to int, because "10" is an int
    

    That's why you can't do :

    byte b = 10;
    b = b + 1;  // Error, right member converted to int, cannot be reassigned to byte without a cast.
    

    So, if you plan to use bytes or shorts to perform some looping, you won't gain anything.

    for (byte b=0; b<10; b++) 
    { ... } 
    

    On the other hand, if you're using arrays of bytes or shorts to store some data, you will obviously benefit from their reduced size.

    byte[] bytes = new byte[1000];
    int[] ints = new int[1000];  // 4X the size
    

    So, my answer is : it depends :)

提交回复
热议问题