Why do people still use primitive types in Java?

后端 未结 21 2202
暗喜
暗喜 2020-11-22 15:11

Since Java 5, we\'ve had boxing/unboxing of primitive types so that int is wrapped to be java.lang.Integer, and so and and so forth.

I see

相关标签:
21条回答
  • 2020-11-22 15:36

    By the way, Smalltalk has only objects (no primitives), and yet they had optimized their small integers (using not all 32 bits, only 27 or such) to not allocate any heap space, but simply use a special bit pattern. Also other common objects (true, false, null) had special bit patterns here.

    So, at least on 64-bit JVMs (with a 64 bit pointer namespace) it should be possible to not have any objects of Integer, Character, Byte, Short, Boolean, Float (and small Long) at all (apart from these created by explicit new ...()), only special bit patterns, which could be manipulated by the normal operators quite efficiently.

    0 讨论(0)
  • 2020-11-22 15:36

    It's hard to know what kind of optimizations are going on under the covers.

    For local use, when the compiler has enough information to make optimizations excluding the possibility of the null value, I expect the performance to be the same or similar.

    However, arrays of primitives are apparently very different from collections of boxed primitives. This makes sense given that very few optimizations are possible deep within a collection.

    Furthermore, Integer has a much higher logical overhead as compared with int: now you have to worry about about whether or not int a = b + c; throws an exception.

    I'd use the primitives as much as possible and rely on the factory methods and autoboxing to give me the more semantically powerful boxed types when they are needed.

    0 讨论(0)
  • 2020-11-22 15:39

    Because JAVA performs all mathematical operations in primitive types. Consider this example:

    public static int sumEven(List<Integer> li) {
        int sum = 0;
        for (Integer i: li)
            if (i % 2 == 0)
                sum += i;
            return sum;
    }
    

    Here, reminder and unary plus operations can not be applied on Integer(Reference) type, compiler performs unboxing and do the operations.

    So, make sure how many autoboxing and unboxing operations happen in java program. Since, It takes time to perform this operations.

    Generally, it is better to keep arguments of type Reference and result of primitive type.

    0 讨论(0)
提交回复
热议问题