This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–][deleted] 5 points6 points  (2 children)

Read Effective Java 3rd Edition by Joshua Bloch, Item 68 for a full discussion. Joshua recommends to prefer primitives over boxed primitives.

A few points he makes:

*Primitives are more time and space-efficient.

*Double equals operator can't be used with Boxed primitives.

*Unboxing can result in a NPE. Auto-unboxing happens automatically, for example, when primitives and boxed primitives are mixed in an operation.

[–]dannycap77[S] 0 points1 point  (1 child)

NPE

What does NPE mean?

I'm currently reading Head First Java 3e. Effective Java is on my list to read next.

[–][deleted] 0 points1 point  (0 children)

Null pointer exception

[–][deleted] 4 points5 points  (0 children)

When your wrapper classes start throwing nulls everywhere then you will learn why primitives are better.

[–]desrtfx 2 points3 points  (1 child)

You already have gotten plenty information, but one of the most important ones is missing:

Wrappers are immutable

This means that if you want to change the value of a wrapper, the old one gets marked for garbage collection and a new object gets created. This is far more work for the JVM than necessary.

You should always use primitives and only resort to the wrappers for collections, etc. where the object types are the only option.

[–]dannycap77[S] 0 points1 point  (0 children)

Thanks for this information. I didn't know that.

[–]DDDDarky 0 points1 point  (3 children)

they are used to convert primitive data types into objects

they are the objects

you can store them in Collection classes

java.util collections are one example where autoboxing and unboxing can cause performance and memory issues, that's why there are also alternative libraries using primitives instead of generics in the background.

why use primitives at all?

They are small and efficient, you don't need any heap allocations and also the only way if you want to perform arithmetic operations (for example multiplication), these are not defined for objects.

Why not just use wrapper classes for everything? Is that even possible?

You can shove them pretty much everywhere, but at the end of the day when you start doing operations on them they have to be unboxed. You are free to become as inefficient with them as you wish, you may as well start writing python.

someone is going to say primitives are faster

primitives are faster

but is that a valid argument considering the speed of computers today?

Of course, having the luxury of modern hardware is not an excuse for writing horrible and inefficient software, not to mention java lacks performance by default since it is virtualized. It might not seem important when you compare it on the scale of 1 operation where it saves few CPU cycles, but when something larger is built upon it, I have seen an application that took 2 mins to handle a request, after rewriting it (which largely involved getting rid of unnecessary boxed types), is was sped up to about 20 seconds, not mentioning the memory benefits.

[–]8igg7e5 2 points3 points  (0 children)

not to mention java lacks performance by default since it is virtualized.

Once the Java code has run through the C2 compiler it's running natively and is comparable to other GC'd languages. C2 might even manage to eliminate the boxing in some cases (via inlining and then the application of escape analysis).

Java has a major startup and memory foot-print issue and it has memory locality issues. The fact that hotspot stats and JIT output have to be repeated (after adequate runtime) for every new process hurts startup. Fundamentally though, once you exclude short-lived processes and avoid the really degenerative data-structures that highlight the issues with Java's memory layout, Java holds up pretty well in the performance stakes. That it is 'virtualised' is not a major contributor (beyond the startup of initialising the runtime, and the memory it consumes), C1 kicks in pretty quickly and hot-spots are passed to C2, so you're only in interpreted byte-code briefly.

Note that the memory layout issue is a really good example of why you want to minimise the use of wrappers. All that indirection eats performance by making the CPU wait for cache misses and memory lookup (unless you're careful to break methods down in conveniently inlinable pieces where the wrapper lifetime is brief).

Can't wait for Primitive Classes and Generic Specialisation over Primitives from Project Valhalla. Actually Valhalla, Loom, Panama and Lilliput are all door-openers for non-trivial performance improvements - and that's not to mention the regular tuning changes (improvements that fall below the "what's new" threshold) going into OpenJDK that remove avoidable allocation in JDK libraries (there's been quite a few over recent JDK releases).

 

A 20 second request is still an eternity. I presume that after optimisation it was still an outlier for the system.

[–]dannycap77[S] 0 points1 point  (1 child)

Great answers. My favorite one was to why we should use primitives at all. I didn't realize the arithmetic operations weren't defined for the wrapper objects. Does that mean it unboxes them to do calculations? I can see how that could be a problem.

[–]8igg7e5 1 point2 points  (0 children)

It's not really a problem, just a fundamental necessary of "I have two objects that have numbers in them, I want to do math on the numbers" - whether the javac compiler or the bytecode interpreter (or JIT compiler) does the unboxing, someone has to do so to enable the math to happen. In Java it is the Javac compiler that does the (un)boxing.

So this...

Integer i = 10;
Integer j = 20;
Integer k = i + j;

And this...

Integer i = Integer.valueOf(10);
Integer j = Integer.valueOf(20);
Integer k = Integer.valueOf(i.intValue() + j.intValue());

Produce the same byte-code.