Performance Implications of Autoboxing

The autoboxing feature was introduced to Java for programmer convenience, particularly in the Collections classes that provide ready-made data structures for use on Objects. Where the intent is obvious, you no longer have to write it all out explicitly.

Just because you don't write the code explicitly, it doesn't mean the code goes away. The compiler generates actual instructions for the implied type promotions between a primitive and its object wrapper.

Those actual instructions have a performance cost at run-time, even though you don't see them at compile time. Take this autoboxing, for instance:

Integer myInt = i; //  autobox!

The compiler will treat that the same way as if you had written a constructor call:

Integer myInt = new Integer(i);

When a constructor is invoked, it causes a chain of calls to constructors in successively higher parent classes back until a constructor in java.lang.Object is invoked. The parent class of Integer is java.lang.Number, and the parent of Number is java.lang.Object. So there are three constructor calls, a memory allocation, and an assignment in that innocuous-looking autoboxing.

CPU cycles get cheaper every year, but they're not completely free or infinitely fast. Be aware of the cost of autoboxing, and avoid doing it unnecessarily or in a loop. Autoboxing costs no more and no less than the equivalent explicit statements. But it's easy to inadvertently overlook the cost of statements that aren't written explicitly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.211.106