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

Ok, so I understand that Integer is just a wrapper class. however my concern is that by avoiding the use of a "wrapper" there could be micro-optimization at runtime when using primitive ints variables.

My question is about the Integer object itself, which we prefer to use, especially in programs that require a lot of performance (with big, I mean, super-powerful, O (N ^ n) algorithms, the ones that take days).

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

+3


source to share


3 answers


You should use primitives whenever you can. Otherwise, they would not exist. The Java devs even put extra effort into developing (for Java 8) streams that support primitive types (IntStream, LongStream, DoubleStream), so you don't have to pay the multi-box performance penalty and hacks that you pay when using Streams of reference types for classes- shells.



Wrappers are only for cases where you have no choice (for example, you cannot inject primitive types directly into the collection).

+8


source


An instance of a wrapper class takes more memory (terminated value + reference) and generates some method calls where primitive types do only 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 with new

). The difference is probably small, but where you can use primitives, do it simply by the principle: don't use classes that provide more features that you need.



+2


source


Prefers int

- Integer

if null is not valid or will be put into the collection.

+1


source







All Articles