简体   繁体   中英

In Java, should Integer object be preferred over int primitive (same for other numeric types)?

Ok, so I understand that Integer is simply a wrapper class. however my concern is that avoiding to use a "wrapper", there might be a micro-optimization in execution time when using primitive ints variables.

My question is regarding, is really Integer object the one we should prefer to use, specially in programs which are required to have great performance(with great I mean, heavy duty, O(N^n) algorithms, the ones that take days).

Also, same case for double vs Double, float vs Float , etc.

You should prefer using the primitives whenever you can. Otherwise they wouldn't exist. The developers of Java even made extra effort in developing (for Java 8) Streams that support primitive types (IntStream, LongStream, DoubleStream), so you won't have to pay the performance penalty of multiple boxings and unboxings that you pay when using Streams of reference types for wrapper classes.

The wrappers are only for cases in which you have no choice (for example, you can't put primitive types directly in a Collection).

A wrapper class instance takes more memory (wrapped value + reference), and generates some method calls where the primitive types only perform basic operations. However, some mechanisms tend to reduce this overhead (for example, Integer instances between -128 and 127 are kept in a pool if not declared using new ). The difference is probably slight, but where you can use primitives, do it simply by principle : don't use classes that provide more features that you need.

首选int to Integer除非null是有效值,否则它将被放置在集合中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM