The statement is generally correct and a good point to consider for performance optimization. Let's break down why:
-
toList() (especially since Java 8 with Streams): toList() applied to a stream is designed to collect elements into a new list efficiently. Java can internally optimize this operation, especially in parallel streams, by:
- Knowing the size upfront (or estimating reasonably): If the stream source has a known size,
toList() can pre-allocate the list to the exact required size, avoiding reallocations as elements are added.
- Parallelization: For parallel streams,
toList() can collect elements into separate intermediate lists in different threads and then efficiently merge them at the end.
-
forEach(List::add): This approach forces you to iteratively add elements to an existing list. Here's why it's potentially problematic:
- No Size Prediction: You're adding elements one by one, so the list implementation (like
ArrayList) might need to resize its underlying array as you go, leading to performance overhead. Each resize operation requires creating a new, larger array and copying all existing elements.
- Impedes Parallelization: If you're using a parallel stream,
forEach would typically require synchronization to safely add to the same list from multiple threads. This synchronization can introduce significant overhead and reduce the benefits of parallelism. Even if the list is thread-safe (like CopyOnWriteArrayList), the thread safety mechanisms themselves can be costly.
- Not Bulking: The core issue is that
forEach is doing one element at a time, preventing "bulking." Bulking refers to Java's ability to perform operations on chunks of data at once, which is generally more efficient.
Example to Illustrate:
Imagine you have a stream of 1 million integers and you want to create a list containing only the even numbers.
Bad (less efficient):
List<Integer> evenNumbers = new ArrayList<>();
IntStream.range(0, 1_000_000)
.filter(i -> i % 2 == 0)
.forEach(evenNumbers::add);
Good (more efficient):
List<Integer> evenNumbers = IntStream.range(0, 1_000_000)
.filter(i -> i % 2 == 0)
.boxed() // Important: need to box to Integer
.collect(Collectors.toList());
Key Considerations:
- Mutability:
toList() creates a new list. If you're modifying an existing list, toList() won't be a direct replacement. You might still be able to achieve better performance with intermediate collections and merges, but it becomes more complex.
- List Implementation: The specific list implementation matters. For example, if you're adding to a
LinkedList, the resizing overhead is less of an issue because LinkedList doesn't rely on contiguous arrays. However, even with LinkedList, toList() is generally preferable for its internal optimizations.
- Parallel Streams: The performance difference is most significant when dealing with parallel streams. Using
forEach with a shared list in a parallel stream is almost always a bad idea.
- Premature Optimization: As always, don't prematurely optimize. If the performance difference is negligible for your use case, readability and code simplicity might outweigh the potential performance gains. Measure the performance impact before making significant changes. Use profiling tools to identify bottlenecks.
In Summary:
The statement is a valuable guideline. Prefer toList() (or other bulk collection methods like Collectors.toSet(), Collectors.toMap(), or custom collectors) over forEach(List::add) when possible. It's generally more efficient, especially with streams, and allows Java to leverage internal optimizations for collecting elements into a list. Be mindful of the specific context, list implementation, and potential need for modification of an existing list, and always profile your code to confirm your assumptions about performance.