repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/skills/performance-optimization/performance-java.md

Raw

Java Performance Optimization

Method Dispatch

The JVM JIT compiles hot code paths. Understanding dispatch helps you write code that compiles efficiently.

Dispatch Types

Type Implementations JIT Behavior Relative Cost
Monomorphic 1 Inlined 1x
Bimorphic 2 Inlined with type guard ~1.2x
Megamorphic 3+ Virtual call (no inline) ~2x

Monomorphic (1 type)

Single implementation at a call site: JIT inlines the call.

// JIT inlines this
interface Coder { int work(byte[] data); }
class Coder0 implements Coder { ... }
Coder c = new Coder0();
c.work(data);  // Fast: inlined

Bimorphic (2 types)

Two implementations seen: JIT generates a type check + both inlined branches.

// Two types seen at call site
interface Coder { int work(byte[] data); }
class Coder0 implements Coder { ... }
class Coder1 implements Coder { ... }
// JIT generates two inlined paths + type check

Megamorphic (3+ types)

Three or more types: JIT cannot optimize, falls back to virtual call.

// Slow: megamorphic dispatch
interface Coder { int work(byte[] data); }
// Three or more implementations used -> virtual call

Benchmarks (non-inlined)

Benchmarks (inlined)

Key insight: Type guards (for bimorphic) still allow inlining and are fast. Megamorphic cannot be inlined - avoid 3+ implementations in hot paths.

Actionable Rules

  1. Use static methods when receiver is known at compile time - fastest dispatch
  2. Limit interface implementations to 2 or fewer for hot paths
  3. Use final classes/methods to enable inlining
  4. Prefer abstract classes over interfaces for performance-critical polymorphism (better CHA)
  5. Batch similar types to keep call sites monomorphic or bimorphic
  6. Deep hierarchies don't matter - hierarchy depth has no impact on call cost
  7. final keyword alone doesn't help - unless combined with refactoring that reduces polymorphism

Garbage Collection

Choose GC based on latency requirements:

GC Use Case Notes
G1 Default server apps Balance throughput/pause
ZGC Ultra-low latency <10ms pauses, any heap size
Shenandoah Low latency Red Hat/SAP JDKs
Parallel Batch/throughput Max throughput, longer pauses

Enable with: -XX:+UseZGC, -XX:+UseShenandoahGC

Memory Optimization

Object Layout

Actionable Rules

  1. Use primitives: int not Integer in hot paths
  2. Use primitive collections: Trove, FastUtil, Eclipse Collections
  3. Avoid String concatenation in loops: use StringBuilder
  4. Prefer arrays over lists for hot paths
  5. Enable compact strings: automatic since Java 9 (ASCII as byte[])

Concurrency

Thread Sizing

Actionable Rules

  1. Use virtual threads (Java 21+) for I/O-bound workloads
  2. Use concurrent collections: ConcurrentHashMap, ConcurrentLinkedQueue
  3. Prefer atomics: AtomicInteger, LongAdder, StampedLock
  4. Avoid synchronization: escape analysis removes locks for thread-local objects

Quick Checklist

Markdown source
# Java Performance Optimization

## Method Dispatch

The JVM JIT compiles hot code paths. Understanding dispatch helps you write code
that compiles efficiently.

### Dispatch Types

| Type        | Implementations | JIT Behavior             | Relative Cost |
| ----------- | --------------- | ------------------------ | ------------- |
| Monomorphic | 1               | Inlined                  | 1x            |
| Bimorphic   | 2               | Inlined with type guard  | ~1.2x         |
| Megamorphic | 3+              | Virtual call (no inline) | ~2x           |

### Monomorphic (1 type)

Single implementation at a call site: JIT inlines the call.

```java
// JIT inlines this
interface Coder { int work(byte[] data); }
class Coder0 implements Coder { ... }
Coder c = new Coder0();
c.work(data);  // Fast: inlined
```

### Bimorphic (2 types)

Two implementations seen: JIT generates a type check + both inlined branches.

```java
// Two types seen at call site
interface Coder { int work(byte[] data); }
class Coder0 implements Coder { ... }
class Coder1 implements Coder { ... }
// JIT generates two inlined paths + type check
```

### Megamorphic (3+ types)

Three or more types: JIT cannot optimize, falls back to virtual call.

```java
// Slow: megamorphic dispatch
interface Coder { int work(byte[] data); }
// Three or more implementations used -> virtual call
```

### Benchmarks (non-inlined)

- Monomorphic: ~2.8 ns/op
- Bimorphic: ~3.3 ns/op
- Megamorphic: ~4.9 ns/op

### Benchmarks (inlined)

- Monomorphic: ~1.6 ns/op
- Bimorphic: ~1.6 ns/op
- Megamorphic: ~4.3 ns/op

**Key insight**: Type guards (for bimorphic) still allow inlining and are fast.
Megamorphic cannot be inlined - avoid 3+ implementations in hot paths.

### Actionable Rules

1. **Use static methods** when receiver is known at compile time - fastest
   dispatch
2. **Limit interface implementations** to 2 or fewer for hot paths
3. **Use final classes/methods** to enable inlining
4. **Prefer abstract classes over interfaces** for performance-critical
   polymorphism (better CHA)
5. **Batch similar types** to keep call sites monomorphic or bimorphic
6. **Deep hierarchies don't matter** - hierarchy depth has no impact on call
   cost
7. **final keyword alone doesn't help** - unless combined with refactoring that
   reduces polymorphism

## Garbage Collection

Choose GC based on latency requirements:

| GC         | Use Case            | Notes                         |
| ---------- | ------------------- | ----------------------------- |
| G1         | Default server apps | Balance throughput/pause      |
| ZGC        | Ultra-low latency   | <10ms pauses, any heap size   |
| Shenandoah | Low latency         | Red Hat/SAP JDKs              |
| Parallel   | Batch/throughput    | Max throughput, longer pauses |

Enable with: `-XX:+UseZGC`, `-XX:+UseShenandoahGC`

## Memory Optimization

### Object Layout

- Object header: 16 bytes on 64-bit (12 header + 4 padding)
- Compressed OOPs: 32-bit pointers if heap < 32GB
- Field padding aligns to 8 bytes

### Actionable Rules

1. **Use primitives**: `int` not `Integer` in hot paths
2. **Use primitive collections**: Trove, FastUtil, Eclipse Collections
3. **Avoid String concatenation in loops**: use `StringBuilder`
4. **Prefer arrays over lists** for hot paths
5. **Enable compact strings**: automatic since Java 9 (ASCII as byte[])

## Concurrency

### Thread Sizing

- **CPU-bound**: threads = CPU cores
- **I/O-bound**: virtual threads scale to thousands (Java 21+)

### Actionable Rules

1. **Use virtual threads** (Java 21+) for I/O-bound workloads
2. **Use concurrent collections**: ConcurrentHashMap, ConcurrentLinkedQueue
3. **Prefer atomics**: AtomicInteger, LongAdder, StampedLock
4. **Avoid synchronization**: escape analysis removes locks for thread-local
   objects

## Quick Checklist

- [ ] Profile first, then optimize
- [ ] Use static methods for known receivers
- [ ] Limit interface implementations to ≤2
- [ ] Use primitives in hot paths
- [ ] Choose right GC for latency needs
- [ ] Use virtual threads for I/O concurrency