Search code examples
javaperformanceinner-classeslombokcoding-efficiency

Performance impact of having inner classes


I would like to know if an inner class would have any impact on performance. Currently I have a class as below.

@Data
@AllArgsConstructor
public class Sample {
    // A total of 9 fields
    // 1. long
    // 2. Enum
    // 3. long
    // 4. int
    // 5. Set<Long>
    // 6. long
    // 7. Enum
    // 8. double
    // 9. long
}

Currently I have just used lombok's @Data and @AllArgsConstructor. The use case is such that I would always have to use the all argument constructor while creating an object of this class.

If I am using @Builder annotation, that would create an inner class. (We have followed the builder pattern for creating objects in most cases).

So in general, does having inner classes have any kind of impact on performance?


Solution

  • To the JVM, there is no such thing as in "inner class", it's just a class (with a funny synthetic name) and (unless it's static) an additional field holding the outer this instance.

    So, the performance impact of using an inner class instead of a stand-alone one should be hardly noticable.

    But creating an instance to hold the call arguments for a method instead of calling the method directly with a long argument list, is inherently slower: you have to create an instance, initialize its fields with the intended method arguments, and the method has to retrieve the arguments from this instance, and finally this instance becomes garbage.

    I agree that long argument lists are a code smell, but introducing a MethodXyArguments class doesn't improve anything, it just hides it under a carpet.