Java garbage collection and temporary objects

I am a C ++ developer by profession, but lately I have been doing a bit of Java development. This project that I am working on has been done by the developer for a long time, and I continue to find things where he works with the Garbage collection, doing strange things.

Case and point he implemented his own class of strings to avoid slowing down the GC

This section of the application takes a large binary file format and exports it to csv. This means creating a line for each line in the file (millions). To avoid these temporary string objects, he created a string class that simply has a large array of bytes that he reuses.

/** HACK A Quick and Dirty string builder implementation optimized for GC. Using String.format causes the application grind to a halt when more than a couple of string operations are performed due to the number of temporary objects allocated while formatting strings for drawing or logging. */ 

Does it help? is it really necessary? Is this better than just declaring a String object outside the loop and setting it inside the loop?

The app also has a hash map containing double values. The keys on the map are pretty static, but the values ​​often change. Afraid of the GC in doubles, he made the myDouble class to use as a value for hashmap

 /** * This is a Mutable Double Wrapper class created to avoid GC issues * */ public class MyDouble implements Serializable { /** * */ private static final long serialVersionUID = C.SERIAL_VERSION_UID; public double d; public MyDouble(double d) { this.d = d; } } 

This is crazy and totally unnecessary ... right?

+6
source share
1 answer

It is true that string concatenation can be a bottleneck in Java because String immutable. This means that each concatenation creates a new String , unless the corresponding String has been created and therefore is in the string pool (see string interning ). In any case, this can lead to problems.

However, your predecessor is not the first person to come across this, and the standard way to deal with the need to concatenate many String in Java is to use StringBuilder .

If a double used as a local variable (or any primitive), it is stored on the stack, and the memory it occupies is freed along with the stack frame (not sure if they are exposed to the GC or the JVM will take care of it). If, however, double is a field on the object, it is stored on the heap and will be assembled when the assembled object is assembled.

Not seeing how double values ​​are used, it's hard to say for sure, but it is more likely that using Map increased the load on the GC.

So, yes, IMHO this, of course, as you say "crazy and completely unnecessary." These types of premature optimizations only complicate the code base, which makes it more error prone and makes future maintenance difficult. The golden rule should be almost always, to build the simplest thing that works, profile it and then optimize.

+3
source

All Articles