Unveiling the Persistence of Primitive Types in Java
Despite the introduction of autoboxing and unboxing in Java 5, primitives continue to hold their ground in many projects. This raises the question: why do developers still favor primitive types over their object counterparts, such as java.lang.Integer.
As outlined by Joshua Bloch in his seminal work "Effective Java," excessive object creation can be detrimental to performance. The following code demonstrates this:
public static void main(String[] args) { Long sum = 0L; for (long i = 0; i <= Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); }
This code, using the Long object, takes approximately 43 seconds to execute. However, converting Long to its primitive type, long, reduces the execution time to a mere 6.8 seconds.
Another consideration is the absence of native value equality in Java. While object equality is performed using equals() method, primitive types use the == operator, which offers a more concise and efficient way to check for equality. Consider the following example:
class Biziclop { public static void main(String[] args) { System.out.println(new Integer(5) == new Integer(5)); System.out.println(new Integer(500) == new Integer(500)); System.out.println(Integer.valueOf(5) == Integer.valueOf(5)); System.out.println(Integer.valueOf(500) == Integer.valueOf(500)); } }
The output reveals that within the range [-128; 127], primitive types return true for equality checks, due to JVM caching. However, beyond this range, objects are created, leading to false results. This caching behavior can introduce inconsistencies in equality checks, which primitive types avoid.
So, while autoboxing and unboxing provide convenience, the performance benefits and efficient equality checks of primitive types continue to make them a viable choice in Java development, even in projects that require Java 5 or later.
The above is the detailed content of Why Do Java Developers Still Prefer Primitive Types Over Wrapper Classes?. For more information, please follow other related articles on the PHP Chinese website!