Course contentsShow
← Java
Lesson 2441 of 2,87046. AnnotationsFree lesson

Retention Policy and Performance Implications

Understand how retention policies affect class file size, memory usage, and reflection overhead.

Retention Policy and Performance Implications

You'll learn: How different retention policies directly affect your application's class file size, memory usage, and reflection performance.

The Performance Cost of Annotations

Not all annotations are created equal when it comes to performance. The @Retention policy you choose determines whether annotations are stored in your .class files and whether they're loaded into memory at runtime—and these decisions have real consequences.

SOURCE: Zero Runtime Cost

Annotations with RetentionPolicy.SOURCE disappear after compilation. They add zero bytes to your class files and consume no runtime memory. Think of them as sticky notes that the compiler reads and then throws away. Perfect for build-time checks like @Override.

CLASS: Disk Cost, Minimal Runtime Impact

RetentionPolicy.CLASS annotations are embedded in your .class files, increasing their size slightly. However, the JVM doesn't load them into memory by default, so they don't affect heap usage or reflection overhead. They're like archived notes stored on disk—present but dormant unless explicitly accessed by bytecode analysis tools.

RUNTIME: The Full Performance Trade-off

RetentionPolicy.RUNTIME annotations have the most significant impact:

  • Class file size: Increases (annotations stored in bytecode)
  • Memory usage: Loaded into the JVM's metadata area alongside class definitions
  • Reflection overhead: Every call to getAnnotation() requires metadata lookup, type instantiation, and proxy creation

If you have hundreds of classes with runtime annotations, you're adding megabytes to your application's memory footprint. Frameworks that scan annotations heavily (like Spring or Hibernate) can experience startup delays from repeated reflection calls.

Choose Wisely

Use SOURCE when possible for compile-time checks. Use RUNTIME only when you genuinely need runtime introspection. The performance difference might seem small per annotation, but it compounds across large codebases.

Key Takeaway: SOURCE retention has zero runtime cost, CLASS adds disk overhead only, and RUNTIME incurs class file, memory, and reflection performance costs—choose the weakest retention policy that meets your needs.