Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use primitives instead of wrapping objects?

Actually here is a similar topic with little practical value. As far as I understand, primitives perform better and should be used everywhere except for the cases where Object-related features (e.g. null check) are needed. Right?

like image 884
yanchenko Avatar asked Oct 27 '08 11:10

yanchenko


People also ask

When should you use primitives?

Object version of primitives are used if you want to express that the value can be null. A primitive is always initialized to zero and thus can never be null. In a RESTful web service java classes are used to model the service request and responses.

Which is better primitive or wrapper class in Java?

Verdict. Generally, choose primitive types over wrapper classes unless using a wrapper class is necessary. Primitive Types will never be slower than Wrapper Objects, however Wrapper Objects have the advantage of being able to be null.

What is the difference between primitive and wrapper class?

Wrapper class creates an object and primitive does not create object. Wrapper classes are used with Collections to represent type. Wrappers have methods and can hold memory address/null and primitives hold default values. Primitives are fast compare to wrapper classes as there is no overhead of methods or object.


1 Answers

Do not forget that, since creating a new wrapper for every boxing occurrence is quite expensive, especially considering it usually being used at a single scope of a method, Autoboxing uses a pool of common wrappers.

This is in fact an implementation of the flyweight design pattern. When a boxing occurs for a well-known value, instead of creating a new wrapper instance, a pre-created instance is fetched from a pool and returned.

One consequence is: it’s still not recommended to use autoboxing for scientific calculations. For example, the code d = a * b + c is using Integer classes for a, b, c and d, and the generated code is d.valueOf(a.intValue() * b.intValue() + c.intValue()). All these method invocations have their own overhead, so it’s usually recommended to use autoboxing when needed to store primitives in collections.

And even then, if you have a huge collection of Integer wrapping int, the overhead can implies longer execution times, up to 20 times longer, as reported in this article.


Jb adds this important comment:

Also Wrapper.valueOf(primitive) uses pool of wrappers. So prefer Integer.valueOf(5) to new Integer(5)

like image 141
VonC Avatar answered Oct 20 '22 00:10

VonC