This is an exact statement from a book on Java. Can someone confirm whether this is indeed right ?
And why does the operation cost done on wrapper classes will be higher than their primitive counterpart ?
This is an exact statement from a book on Java. Can someone confirm whether this is indeed right ?
And why does the operation cost done on wrapper classes will be higher than their primitive counterpart ?
Of course this is right. A lot of things come into picture when you use wrapper classes:
1) Implicit conversion of primitive to Objects, this is not easy a lot of private variables of the wrapper class are populated to create an object for a primitive. Which I believe is an overhead.
2) They also have to take care of null check if it is not primitive, you know to avoid the famous NPE(NullPointerException) , which is an additional overhead.
There are many such reasons, but I believe you got the answer. :)
Why operation cost done on wrapper classes will be higher than ??
Because while run time, If we use Wrappers Boxing conversions and Unboxing Conversions happens at Runtime,Obviously that takes more time.
For Example.
Consider a case with int
and Integer
While run time
If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p
And vice-versa, this time will be saved in case,if we use Primitives
.
Can someone confirm whether this is indeed right?
Yes, one could construct a very crude benchmark to demonstrate that operations on primitives are at least an order of magnitude faster:
// Use a primitive type long
long now = System.currentTimeMillis();
long count = 0;
long total1 = 0;
do {
for (int i = 0 ; i != 1000 ; i++)
total1 += 11;
count++;
} while (System.currentTimeMillis()-now < 2000);
System.out.println("Primitives: "+count+" x1000 additions completed.");
// Use a wrapper type Long
now = System.currentTimeMillis();
count = 0;
Long total2 = 0L;
do {
for (int i = 0 ; i != 1000 ; i++)
total2 += 11;
count++;
} while (System.currentTimeMillis()-now < 2000);
System.out.println("Wrapper: "+count+" x1000 additions completed.");
This produces the following results on ideone:
Primitives: 1125085 x1000 additions completed.
Wrapper: 112760 x1000 additions completed.
As you can see, the primitives are at least ten times faster, even in this very crude test where measuring the time takes a significant portion of the time.
why does the operation cost done on wrapper classes will be higher than their primitive counterpart?
This is easy to explain: in addition to the operation itself that is performed on the primitive, the operation on the wrapper requires these operations:
The allocation operation is particularly expensive compared to the arithmetic operation performed on the value inside the primitive.