Skip to the content.
Memory efficient Java code
- Simple Integer object create 4 times the size of operatiing system OS.
e.g.
Integer integer = new Integer(10), In this example it create 128 bit on 32 bit OS
- Whenever you need a single character for a class try to create char rather than String.
e.g.
String string = new String("myString"), this create another object which is character array which store the actual data.
- Compressed object refrence should be enabled in the 64 bit OS.
- The more GC run will slower the application running.
- Right choice for right collection.
- Heap: clean up done GC.
- Dangling pointer bug: a case where a pointer still pointing to the old place (unpredictable return) freeing up memory twice. There is no pointer reference.
Heap size and relation to GC:
- size of the heap influence GC.
- smaller heap means that GC needs to happen more often (due to too small heap impact performance)
- when heap size is to big, then full GC can take place long
time.
- heap size depends upon application, less that 5% of the execution time should be GC
Sweeping Methods:
- Normal sweep
- sweel with compacting
- sweep with copy
Metric for GC:
- Allocation rate
- Heap population
- Mutation rate
- Object life span
- Mark time
- Compaction time
- GC cycle time
Notes:
- Less memory leads to increased CPU.
- Copy and compact collector need more space.
- Better GC can do the job with more space.
Avoid memory leaks:
- Set the object to null in certain specific situation
- Close resources such as streams and connections
- Avoid string concats; use string builder instead
- Careful with static collections holding objects
- Overwrite hashcode and equals(especially when custom objects get added to hash sets)
In Java 8
- Java has refrence type (Integer, Byte etc) and primitive type (int, byte) and only reference type is bounded to generic type (T) in Java.
- Java has auto boxing and un-boxing but it comes with a cost of storing boxed oject in the heap and consumes more memory. and required additional lookup to fetch wraped primitive value.