You are getting essential things wrong here.
First of all, writing a good micro-benchmark goes way beyond what you are doing in your code; see here for some guidelines.
Then: you have to understand the things you want to benchmark. For example:
public static long wrapper(Integer count)
{
long startTime = System.currentTimeMillis();
for(int i=0;i<10000;i++)
count++
Integer objects are immutable. This code does not only "add" Integer objects, it creates one new Integer object per iteration.
And of course: your code doesn't even use the computation result. If the JVM/JIT notices that, it might completely throw away that looping and adding construct. So your methods should at least return the final value of count; and the caller should print that result.
And to answer your specific question: of course using the reference type wrapper classes comes at certain cost. When your program is dealing with (really) high numbers of elements to work on, then using a List of Integer does have considerable higher cost than using an array of int for example. And when you don't pay attention and you are doing implicit autoboxing/unboxing in your code, that can really hurt.
But the real answer here is: you are focusing on the wrong thing. You see, your first priority should be to do a great design, followed by a well-tested, robust, readable, maintainble implementation. Of course, you should not do outright stupid things and waste performance, but well, before you worry about performance, you better worry about your Java skills in general.
Long story short: focus on understanding java and on "how do I create a good design"; and forget about "performance" for now. You only have to deal with "performance" when it is a real issue in your application. And then you do real profiling in order to identify the root cause and fix that.
Answer from GhostCat on Stack Overflowinteger - What is the real difference between primitives and wrapper classes in Java - Stack Overflow
java - Primitive variables perform calculations faster than their associated wrapper class - Stack Overflow
java - When to use wrapper class and primitive type - Stack Overflow
When to use primitive vs class in Java? - Software Engineering Stack Exchange
Which is faster: primitives or wrappers?
What is the key difference between primitives and wrapper classes?
Why do frameworks like Hibernate prefer wrappers over primitives?
Videos
The real difference is that primitive types are not reference types.
In Java type system, reference types have a common root, while primitive types do not: All reference types are subtypes of Object. In comparison, primitive types do not have a common root; each primitive type is its own special unicorn.
This means that a variable declared with Object type can hold a value of any reference type, but it cannot hold a value of any primitive type.
This is a problem if you want to create data structures that are generally useful. Consider how you would implement a "dynamic array" data structure like ArrayList or Vector. You could use an array Object[] to store the elements, and that would work for all reference types. But since primitive types don't have a common root you would have to create a separate implementation for each primitive type.
To solve this problem, wrapper classes were created. Now, instead of needing 8 separate implementations of dynamic array (1 for reference types and 7 for primitive types), you could wrap each primitive value in an object, and just use the implementation for reference types.
Primitive types and wrapper classes were created at the same time, when the first design and implementation of Java 1.0 were made. The designers did not "reuse what was already available" because nothing was available: they built everything from scratch.
Could the designers have solved the problem some other way, maybe by creating a type system that had a common root for both primitive and reference types? Yes, but they didn't, and they probably had good reasons: implementation complexity, ease of understanding, time to market, ...
Actually, this question is pretty insightful. The answers are good and correct, but the underlying question that I think is worth asking is: should primitive types exist at all? We had a lot of discussion about this at the time and I think the reason things ended up the way they did had to do with the fact that Oak (later Java) was designed as an embedded language for the IOT (internet of things). If it had been originally designed as a server language, it might have been very different. I think primitive types are a legacy idea that is actually very harmful for exactly the reasons that Joni mentions. It's possible and desirable to have everything in the system extend Object.
How could you eliminate primitives? With a smarter JVM. HotSpot could turn special primitive objects into appropriate machine code wherever possible and there wouldn't be a need for autoboxing, wrappers or difficulties with the type system being split. The only limitation that I think would need to be placed on Integer, Float, Double, etc., is that they would have to be final. This would allow these classes to be optimized anywhere possible as if they were primitives without actually having primitives in the language. You could even have syntactic abbreviations like 'int', 'float' and 'double' for these special classes, but the important thing is that the type system would be better if it was fully unified.
But you don't start trying to build such a thing when you're thinking about smart toasters. What happened to Java in terms of its wild success was a pure accident. It happened to be a solution to a lot of web-related issues just sitting there at the right time. But it wasn't planned that way, so there are a lot of things people would like to have back. I think a lot of people at Sun/Oracle would eliminate primitives in hindsight.
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.
Others have mentioned that certain constructs such as Collections require objects and that objects have more overhead than their primitive counterparts (memory & boxing).
Another consideration is:
It can be handy to initialize Objects to null or send null parameters into a method/constructor to indicate state or function. This can't be done with primitives.
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
This will also set the scene for a NullPointerException when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.
Generally, you should use primitive types unless you need an object for some reason (e.g. to put in a collection). Even then, consider a different approach that doesn't require a object if you want to maximize numeric performance. This is advised by the documentation, and this article demonstrates how auto-boxing can cause a large performance difference.
In Item 5, of Effective Java, Joshua Bloch says
The lesson is clear: prefer primitives to boxed primitives, and watch out for unintentional autoboxing.
One good use for classes is when using them as generic types (including Collection classes, such as lists and maps) or when you want to transform them to other type without implicit casting (for example Integer class has methods doubleValue() or byteValue().
Edit: Joshua Bloch's reason is:
// Hideously slow program! Can you spot the object creation? public static void main(String[] args) { Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); }This program gets the right answer, but it is much slower than it should be, due to a one-character typographical error. The variable
sumis declared as aLonginstead of along, which means that the program constructs about 2^31 unnecessaryLonginstances (roughly one for each time thelong iis added to theLong sum). Changing the declaration of sum fromLongtolongreduces the runtime from 43 seconds to 6.8 seconds on my machine.
The standard practice is to go with the primitives, unless you're dealing with generics (make sure you are aware of autoboxing & unboxing!).
There are a number of good reasons to follow the convention:
1. You avoid simple mistakes:
There are some subtle, non-intuitive cases which often catch out beginners. Even experienced coders slip up and make these mistakes sometimes (hopefully this will be followed by swearing when they debug the code and find the error!).
The most commmon mistake is using a == b instead of a.equals(b). People are used to doing a == b with primitives so it's easily done when you're using the Object wrappers.
Integer a = new Integer(2);
Integer b = new Integer(2);
if (a == b) { // Should be a.equals(b)
// This never gets executed.
}
Integer c = Integer.valueOf(2);
Integer d = Integer.valueOf(2);
if (c == d) { // Should be a.equals(b), but happens to work with these particular values!
// This will get executed
}
Integer e = 1000;
Integer f = 1000;
if (e == f) { // Should be a.equals(b)
// Whether this gets executed depends on which compiler you use!
}
2. Readability:
Consider the following two examples. Most people would say the second is more readable.
Integer a = 2;
Integer b = 2;
if (!a.equals(b)) {
// ...
}
int c = 2;
int d = 2;
if (c != d) {
// ...
}
3. Performance:
The fact is it is slower to use the Object wrappers for primitives than just using the primitives. You're adding the cost of object instantiation, method calls, etc. to things that you use all over the place.
Knuth's "...say about 97% of the time: premature optimization is the root of all evil" quote doesn't really apply here. He was talking about optimisations which make the code (or system) more complicated - if you agree with point #2, this is an optimization which makes the code less complicated!
4. It's the convention:
If you make different stylistic choices to 99% of the other Java programmers out there, there are 2 downsides:
- You will find other people's code harder to read. 99% of the examples/tutorials/etc out there will use primitives. Whenever you read one you'll have the extra cognitive overhead of thinking about how it would look in the style that you're used to.
- Other people will find your code harder to read. Whenever you ask questions on Stack Overflow you'll have to sift through answers/comments asking "why aren't you using primitives?". If you don't believe me, just look at the battles people have over things like bracket placement, which doesn't even affect the generated code!
Normally I'd list some counter-points, but I honestly can't think of any good reasons to not go with the convention here!
From Effective Java - Joshua Bloch
Item 49- Prefer primitive types to boxed primitives
Use primitives in preference to boxed primitives whenever you have choice. Primitive types are simple and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives
So if your need is not fulfilled by primitives then you use boxed primitives, Like in case of Collections
The choice depends on the need; whether u need primitve or an object. Wrapper classes are there to provide utility methods and also to be used easily in Collections. Depending on your need you should pick from primitives and wrapper classes. The better you chose the lesser will be overheads of autoboxing/auto-unbboxing.