Why do people still use primitive types in Java?

后端 未结 21 2628
暗喜
暗喜 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

    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.

提交回复
热议问题