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?
views:
644answers:
5yes, primitives are faster than objects. Since java 5 you can even mix primitives and objects without manually converting one to another. The autoboxing mechanism takes care of just that.
this means that if you put a primitive in a collection, the compiler will not complain, and convert the primitive to an object implicitly.
Primitives are faster when they are used, as objects need to be unboxed before use; thus there is an extra step for the VM to perform. For example, In order perform arithmetic on an Integer, it must first be converted to an int before the arithmetic can be performed.
In many business applications this probably rarely matters. But if you were writing something very numnber-crunching heavy like, say, a graphics transformation processor you are a lot more likely to care.
I would say you should be worried about using primitives over wrappers only when you profile your application and see that the autoboxing is a performance or memory issue. In my experience memory becomes an issue before CPU cycles when talking about primitives vs wrapping objects.
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)
If you need store primitives in collections you might use commons-primitives.
I prefer using primitives to wrappers, only place that absolutely needs to have wrappers are entity classes. Databases support nulls, so entities should too.
I once worked on project that used primitives (and homebrew ORM) in database access:
class Foo{
int xxx = -1;
...
}
And then you had:
void persist(Foo foo){
...
statement.setInt(15,foo.getXXX()==-1?null:foo.getXXX());
...
}
God it was evil.