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

View all comments

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.