Garbage collection & Just-In-Time (JIT) compilation

Optimizing Code in Java

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

Garbage collection - the basics

Manual Memory Management (C/C++)

  • Programmer allocates & frees memory explicitly
  • Prone to leaks

$$

Java's Garbage Collection

  • Automatic memory allocation
  • Automatic detection of unused objects
  • Automatic memory reclamation
Optimizing Code in Java

How garbage collection works

  • Mark: Identify reachable objects from roots
  • Sweep: Remove unreachable objects

Screenshot 2025-05-11 at 6.58.38?PM.png

Optimizing Code in Java

Garbage collection and performance

GC Performance Trade-offs

  • Simplifies development, but comes with performance considerations

$$

GC Algorithms

  • There are several garbage collection algorithms offered by modern JVMs
  • The choice depends on the application's requirements
  • A deep-dive guide regarding GC algorithms can be found here
1 https://www.baeldung.com/jvm-garbage-collectors
Optimizing Code in Java

GC performance impact

// Bad - Creating many short-lived objects
for (int i = 0; i < 1000000; i++) {
    new Object(); // Immediately becomes garbage
}


// vs. Reusing objects Object obj; for (int i = 0; i < 1000000; i++) { obj = new Object(); // Only one reference }
Optimizing Code in Java

GC-friendly coding

// Avoid this in performance-critical code
String result = "";
for (int i = 0; i < 100000; i++) {
    result += i; // Creates a new String each time
}


// Better approach StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100000; i++) { builder.append(i); // Reuses the same buffer } String result = builder.toString();
Optimizing Code in Java

Just-In-Time compilation

  • JVM execution process:
    • Java source -> Bytecode
    • Bytecode -> Interpreted execution
    • Hot methods -> Native machine code
  • Optimizes frequently executed code
Optimizing Code in Java

JIT-friendly code patterns

  • Write predictable code
// Predictable branches help JIT optimization
if (value > 0) {
    // Code A - frequently taken path
} else {
    // Code B - rarely taken path
}
  • Create focused, smaller methods
  • Small, frequently called methods are ideal candidates for inlining
  • Complex code may be optimized less effectively
Optimizing Code in Java

Summary

  • Minimize object creation in performance-critical paths
  • Write predictable code that aligns with JIT optimization capabilities
  • Focus optimization on the code that actually matters by profiling first
Optimizing Code in Java

Let's practice!

Optimizing Code in Java

Preparing Video For Download...