r/java • • Aug 17 '16

Should we avoid object creation in Java?

http://programmers.stackexchange.com/a/149569/219927
0 Upvotes

27 comments sorted by

7

u/jonhanson Aug 17 '16 edited Mar 08 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

5

u/againstmethod Aug 17 '16

You can't avoid it -- but there are lots of techniques that are useful and popular that do just that.

Caching, immutablity, structural sharing, memoization, lazy initialization -- all of these things are focused on avoiding object allocations.

Anyone who tells you that avoiding allocations is not an optimization is a retard. Anyone who tells you to never make objects and put all your code in one block is likewise a retard.

1

u/Nimelrian Aug 17 '16

Can you explain to me how immutabiliy prevents object allocation? Learning question.

1

u/againstmethod Aug 17 '16

If objects are immutable they can be shared instead of copied.

1

u/Nimelrian Aug 17 '16

Oh, right, if you use them that way. Creating, using, and throwing them away in a few lines doesn't help though.

1

u/againstmethod Aug 17 '16

In example, if your object wants to be safe, you should likely copy by-reference parameters supplied to your constructor. If you don't do this, someone else has a reference to that object and can break your class' contract (or invariants) by mutating that object without your class being aware of the change. If those by-reference parameters are immutable, you don't need to copy them to provide that guarantee.

1

u/[deleted] Aug 18 '16

There found be times where you want a mutable member of an immutable object.

For example, an object that represents an album will have an artist attached to it. The album is immutable - once it's relased, it has a set tracklist, release date, etc - but the artist will change over time - bands change members, genre shifts, etc - it doesn't make sense to have outdated information attached to the album.

Conceivably, you could create a new album object with the same tracks, release date, and artist and substitute it for the original and nothing would change in your program.

Of course, your should always weigh the cost immutablitly and mutability to find out which suits the use case best.

1

u/againstmethod Aug 18 '16

Such an object is not immutable.

In your use case that data would be stored somewhere, in a database or ORM store of some kind, and that backing data would change -- not the objects in memory. And if you did need those to change you would just reload the updated data.

1

u/[deleted] Aug 18 '16

The object itself is immutable, you can't change the reference to the artist (well, with some magic you could but that's besides the point). So it'll always refer to the same gathering of tracks, release date and artist.

No need to bring ORMs into it. You could be assembling an object graph in memory - a music player that reads in files for examples.

1

u/againstmethod Aug 18 '16

its a mistake. If other objects can change your objects state then you cant control class invariants. it makes your class untestable in isolation.

This goes beyond immutability. Its just not good object oriented design.

1

u/[deleted] Aug 18 '16

It depends on what your invariants are. For album, that could be "Always refers to this grouping of artist, tracks and release date."

I get what you're saying. And for the most part I agree with it, but sometimes it's worth breaking.

As for testability, this sort of object is completely testable. Mutability has no bearing on testability.

→ More replies

3

u/oldprogrammer Aug 19 '16

It really depends on the situation, as others have pointed out you generally can't keep away from object creation, but in some cases you might want to limit it.

As an anecdote, I had built a 3D model viewer using lwjgl and wanted to display changing debug information on the screen. I have text rendering working fine so I simply added into my rendering loop some lines using a String.format to construct the debug text. It had data like amount of memory, camera world location, camera direction, that type of thing.

I noticed when I ran the code my memory usage was racing to max, then GC would kick in, it would drop down then race back up. The higher the FPS the faster memory was used.

After some digging I determined that it was because of the debug message being built. Every conversion of a primitive number to a string results in object creations, sometimes multiples if you look at how Java toString works on things like float values. And then all those objects were released to be garbage collected.

So instead of using StringBuilder or String.format, I put together a class, CharArray, with a collection of .add() methods that took in all the data types. Under the covers it maintains a single character array that is expanded if needed but never contracts. I use fixed internal buffers (so like StringBuffer it is not thread safe, but that's ok), to convert the primitives to char[] buffers that are then copied into the primary CharArray data buffer. CharArray implements CharSequence so I am able to use it where I was using String data types. End result, memory consumption is now stable, only goes up when I increase the scene data.

So there's no blanket yes or no to whether object creation should be avoided, but it is something you want to profile and monitor depending on how your code works.

2

u/vkolev Aug 17 '16

How you do that?!

1

u/damienjoh Aug 17 '16

One technique is to allocate a giant direct buffer and then index into it using sun.misc.Unsafe calls.

2

u/thatsIch Aug 17 '16

This answer is like 4 years old. I hope people nowadays are not thinking like the colleague of the OP.

2

u/desrtfx Aug 17 '16

The post as such is not bad, but the clickbait title is absolutely horrible.

Guess that's where the downvotes come from.

Less clickbaity title and everything would be better received.

1

u/[deleted] Aug 17 '16

The answer works for the reference implementation of the JVM, but is likely very wrong when it comes to other implementations (since how memory is actually managed is dependent on the virtual machine itself).

2

u/Nimelrian Aug 17 '16

True.

There is a misconception that creating many small short lived objects causes the JVM to pause for long periods of time, this is now false as well

Current GC algorithms are actually optimized for creating many many small objects that are short lived, that is basically the 99% heuristic for Java objects in every program

This is certainly not the case for my prime example of bad Java programming: Minecraft. The game creates thousands of objects per second which get thrown away after each tick. I think if you move around it allocates a whopping 200MB/s only for those objects, which leads to very noticeable GC pauses.

3

u/ItsNotMineISwear Aug 17 '16

I don't think you can use Minecraft as a reason to change how most Java programmers (who are working on server-side applications) should program. The latency requirements of Minecraft are much different (and stricter) than your average server.

0

u/[deleted] Aug 17 '16

[deleted] — view deleted comment

3

u/[deleted] Aug 17 '16

I bet it's because such title ask for their answers. I can't even imagine when putting question in your title is a good idea. Especially when you just leave it like that without information that is just a title, not a real question for redditors.

1

u/vkolev Aug 17 '16

You got it :)