Course contentsShow
← Java
Lesson 1495 of 2,87033. Streams API: Terminal OperationsFree lesson

Performance Considerations with forEach

Understand forEach overhead versus traditional loops and when to use collect instead of forEach for building results.

Performance Considerations with forEach

You'll learn when forEach creates unnecessary overhead and when to choose alternatives for better performance.

While forEach is convenient for side effects, it's not always the most efficient choice. Understanding its performance characteristics helps you write faster, cleaner code.

forEach Overhead vs Traditional Loops

forEach involves creating lambda expressions or method references, which adds a small overhead compared to traditional for or enhanced for loops. For simple iterations over collections, this overhead is usually negligible. However, when processing millions of elements in performance-critical code, a traditional loop might be measurably faster because it avoids the lambda invocation cost.

// Traditional loop - slightly faster for simple iteration
for (String item : list) {
    System.out.println(item);
}

// forEach - cleaner but adds lambda overhead
list.forEach(System.out::println);

The Anti-Pattern: Building Results with forEach

A common mistake is using forEach to build collections:

// AVOID: Using forEach to build results
List<String> results = new ArrayList<>();
stream.forEach(item -> results.add(item.toUpperCase()));

This is problematic because:

  • forEach is designed for side effects, not producing results
  • You're modifying external state from within the lambda
  • It breaks the functional programming style Streams promote
  • collect is specifically optimized for this task
// BETTER: Use collect for building results
List<String> results = stream
    .map(String::toUpperCase)
    .collect(Collectors.toList());

The collect operation is designed to accumulate results efficiently, often with optimized internal buffering and parallel-safe accumulation.

Key Takeaway: Use forEach only for genuine side effects like printing or logging. When building collections or computing aggregated results, use collect or other appropriate terminal operations—they're both clearer and more performant.