java short,integer,long performance

前端 未结 6 701
我在风中等你
我在风中等你 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-02 00:14

    I agree with user2391480, calculations with shorts seem to be way more expensive. Here is an example, where on my machine (Java7 64bit, Intel i7-3770, Windows 7) operations with shorts are around ~50 times slower than integers and longs.

    public class ShortTest {
    
    public static void main(String[] args){
        calculate();
        calculate();
    }
    
    public static void calculate(){
        int N = 100000000;
    
        long time1=System.currentTimeMillis();
        short s=0;
        for(int i = 0; i

    }

    Output:

    Time elapsed for shorts: 113
    Time elapsed for ints: 2
    Time elapsed for longs: 2
    0
    Time elapsed for shorts: 119
    Time elapsed for ints: 2
    Time elapsed for longs: 2
    0
    

    Note: specifying "1" to be a short (in order to avoid casting every time, as suggested by user Robotnik as a source of delay) does not seem to help, e.g.

        short s=0;
        short one = (short)1;
        for(int i = 0; i

    EDIT: modified as per request of user Hot Licks in the comment, in order to invoke the calculate() method more than once outside the main method.

提交回复
热议问题