1. Stop using LinkedList for anything but heavy removing from the middle of the list using iterator.

  2. Stop writing benchmarking code by hand, use JMH.

Proper benchmarks:

@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
@OperationsPerInvocation(StreamVsVanilla.N)
public class StreamVsVanilla {
    public static final int N = 10000;

    static List<Integer> sourceList = new ArrayList<>();
    static {
        for (int i = 0; i < N; i++) {
            sourceList.add(i);
        }
    }

    @Benchmark
    public List<Double> vanilla() {
        List<Double> result = new ArrayList<>(sourceList.size() / 2 + 1);
        for (Integer i : sourceList) {
            if (i % 2 == 0){
                result.add(Math.sqrt(i));
            }
        }
        return result;
    }

    @Benchmark
    public List<Double> stream() {
        return sourceList.stream()
                .filter(i -> i % 2 == 0)
                .map(Math::sqrt)
                .collect(Collectors.toCollection(
                    () -> new ArrayList<>(sourceList.size() / 2 + 1)));
    }
}

Result:

Benchmark                   Mode   Samples         Mean   Mean error    Units
StreamVsVanilla.stream      avgt        10       17.588        0.230    ns/op
StreamVsVanilla.vanilla     avgt        10       10.796        0.063    ns/op

Just as I expected stream implementation is fairly slower. JIT is able to inline all lambda stuff but doesn't produce as perfectly concise code as vanilla version.

Generally, Java 8 streams are not magic. They couldn't speedup already well-implemented things (with, probably, plain iterations or Java 5's for-each statements replaced with Iterable.forEach() and Collection.removeIf() calls). Streams are more about coding convenience and safety. Convenience -- speed tradeoff is working here.

Answer from leventov on Stack Overflow
🌐
InfoWorld
infoworld.com › home › software development › programming languages › java
High-performance programming with Java streams | InfoWorld
December 18, 2025 - Parallelism produces real performance gains only for CPU-bound, stateless computations on large datasets. For lightweight or I/O-bound operations, the overhead of thread management often outweighs any benefits. The program below simulates CPU-intensive work for each element and measures execution time with both sequential and parallel streams: import java.util.*; import java.util.stream.*; import java.time.*; public class ParallelThresholdDemo { public static void main(String[] args) { List<Integer> sizes = List.of(10_000, 100_000, 1_000_000, 10_000_000); for (int size : sizes) { List<Integer>
Top answer
1 of 6
225
  1. Stop using LinkedList for anything but heavy removing from the middle of the list using iterator.

  2. Stop writing benchmarking code by hand, use JMH.

Proper benchmarks:

@OutputTimeUnit(TimeUnit.NANOSECONDS)
@BenchmarkMode(Mode.AverageTime)
@OperationsPerInvocation(StreamVsVanilla.N)
public class StreamVsVanilla {
    public static final int N = 10000;

    static List<Integer> sourceList = new ArrayList<>();
    static {
        for (int i = 0; i < N; i++) {
            sourceList.add(i);
        }
    }

    @Benchmark
    public List<Double> vanilla() {
        List<Double> result = new ArrayList<>(sourceList.size() / 2 + 1);
        for (Integer i : sourceList) {
            if (i % 2 == 0){
                result.add(Math.sqrt(i));
            }
        }
        return result;
    }

    @Benchmark
    public List<Double> stream() {
        return sourceList.stream()
                .filter(i -> i % 2 == 0)
                .map(Math::sqrt)
                .collect(Collectors.toCollection(
                    () -> new ArrayList<>(sourceList.size() / 2 + 1)));
    }
}

Result:

Benchmark                   Mode   Samples         Mean   Mean error    Units
StreamVsVanilla.stream      avgt        10       17.588        0.230    ns/op
StreamVsVanilla.vanilla     avgt        10       10.796        0.063    ns/op

Just as I expected stream implementation is fairly slower. JIT is able to inline all lambda stuff but doesn't produce as perfectly concise code as vanilla version.

Generally, Java 8 streams are not magic. They couldn't speedup already well-implemented things (with, probably, plain iterations or Java 5's for-each statements replaced with Iterable.forEach() and Collection.removeIf() calls). Streams are more about coding convenience and safety. Convenience -- speed tradeoff is working here.

2 of 6
20

1) You see time less than 1 second using you benchmark. That means there can be strong influence of side effects on your results. So, I increased your task 10 times

    int max = 10_000_000;

and ran your benchmark. My results:

Collections: Elapsed time:   8592999350 ns  (8.592999 seconds)
Streams: Elapsed time:       2068208058 ns  (2.068208 seconds)
Parallel streams: Elapsed time:  7186967071 ns  (7.186967 seconds)

without edit (int max = 1_000_000) results were

Collections: Elapsed time:   113373057 ns   (0.113373 seconds)
Streams: Elapsed time:       135570440 ns   (0.135570 seconds)
Parallel streams: Elapsed time:  104091980 ns   (0.104092 seconds)

It's like your results: stream is slower than collection. Conclusion: much time were spent for stream initialization/values transmitting.

2) After increasing task stream became faster (that's OK), but parallel stream remained too slow. What's wrong? Note: you have collect(Collectors.toList()) in you command. Collecting to single collection essentially introduces performance bottleneck and overhead in case of concurrent execution. It is possible to estimate the relative cost of overhead by replacing

collecting to collection -> counting the element count

For streams it can be done by collect(Collectors.counting()). I got results:

Collections: Elapsed time:   41856183 ns    (0.041856 seconds)
Streams: Elapsed time:       546590322 ns   (0.546590 seconds)
Parallel streams: Elapsed time:  1540051478 ns  (1.540051 seconds)

That' s for a big task! (int max = 10000000) Conclusion: collecting items to collection took majority of time. The slowest part is adding to list. BTW, simple ArrayList is used for Collectors.toList().

Discussions

Java Stream drastically increases execution time compared to for loop
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
23
19
November 3, 2024
For daily Java programmers: after almost one decade of Java 8, are streams and lambdas fully adopted by the Java community?
Depends on what you mean by fully adopted. If you mean that all 100% of Java developers are using it, then No. and if you mean that streams and lambdas are being used all 100% of the time, then No. :) Java dev community is huge. There are millions of developers. So there will be a case that some of them can’t use Java 8 and some of them don’t want to use streams and lambdas. Also streams and lambdas are good for specific situations. Streams are good for filter, map, reduce operations and lambdas are good for moving functions around (as first class citizens). There might still be places where stream may not be a best option. So it’s highly likely that the answer to your question is No which may not necessarily be a bad thing. More on reddit.com
🌐 r/java
211
148
March 30, 2023
Java 8 lambda performance is not great

My assumption is, that Lambdas are a new feature, and JVM optimization are not at the level of native loops yet.

Also you use different method calls in comparison. If you use Double::compare you can not compare it with d < min in performance.

More on reddit.com
🌐 r/java
26
11
January 18, 2015
How fast are the Java 8 Streams compared to for-loops?
I see this come up a lot. And almost every time they overlook one very important fact. Unless you are doing something that is very critical, the performance of your loops doesn't really matter that much. What matters so much more is the performance of your developers. I.e. the ability for people to read, understand, produce, debug, etc the code that is being run. This example shows that it takes 5ms to reduce 500,000 integers. 5ms. That's 1ns per integer in the array. That's nothing to worry about at all. Compare that instead to the cost to the developer of reading int m = Integer.MIN_VALUE; for (int i = 0; i <= ints.length; i++) if (ints[i] > m) m = ints[i]; as opposed to reading int m = Arrays.stream(ints) .reduce(Integer.MIN_VALUE, Math::max); Which one is more readable? Which one is more likely to have subtle bugs that aren't obvious? Did you even notice that there's an off-by-one error in my example above? And that to save a runtime cost of 5 one-thousandths of one second. More on reddit.com
🌐 r/java
44
94
November 27, 2015
🌐
DZone
dzone.com › coding › javascript › performance with java8 streams
Performance With Java8 Streams
November 6, 2017 - In Java8 Streams, performance is achieved by parallelism, laziness, and using short-circuit operations, but there is a downside as well, and we need to be very cautious while choosing Streams, as it may degrade the performance of your application.
🌐
Medium
medium.com › @BuildandDebug › the-three-traps-of-java-stream-performance-and-how-to-avoid-them-241b76d8c443
The Three Traps of Java Stream Performance (And How to Avoid Them) | by Build & Debug | Medium
July 25, 2025 - We will dissect the three most common performance traps and provide clear rules for avoiding them. The .parallel() method is tempting. With a single method call, you can theoretically leverage multi-core processors to speed up your work. The reality is far more nuanced. Parallel streams are not a magic bullet; they are a specialized tool.
🌐
Belief Driven Design
belief-driven-design.com › how-fast-are-streams-really-ad9cc
How Fast Are Streams Really? | belief driven design
April 29, 2025 - Streams offer tremendous advantages in modern Java development. Their performance is generally excellent and often statistically indistinguishable from loops for many common scenarios, especially once dataset sizes grow beyond a handful of elements.
🌐
Harness
harness.io › blog › service reliability management › benchmark: how misusing streams can make your code 5 times slower
Benchmark: How Misusing Streams Can Make Your Code 5 Times Slower
February 11, 2026 - Java 8's lambda expressions and ... can lead to a 5x performance hit compared to traditional imperative methods like iterators and for-each loops in tasks such as finding a max value in an ArrayList....
🌐
amitph
amitph.com › home › java › java 8 streams - laziness and performance
Java 8 Streams - Laziness and Performance - amitph
November 22, 2024 - In the Java 8 Streams API, the intermediate operations are lazy and their internal processing model is optimised to make it being capable of processing the large amount of data with high performance.
Find elsewhere
🌐
SoftwareMill
softwaremill.com › benchmarking-java-streams
Benchmarking Java Streams | SoftwareMill
May 23, 2024 - Where best performance belongs to bench_parallelStreamWithCustomForkJoinPool_16 which may indicate that in the end, reasonably smaller parallelism may be a good idea. The Fork/Join-based implementation is noticeably slower than default parallel stream implementation, with around 10 % worse performance.
🌐
Medium
medium.com › @daniel.las › speed-of-java-stream-1cc3a94b44c2
Speed of Java stream. Is Java Stream API nice but slow… | by Daniel Las | Medium
May 24, 2024 - Vavr's Map has effectively constant get and put operations performance characteristics and we have to always call them both, because there is no similar to plain Java's Map.compute() operation available in its API. I wouldn’t like to draw any significant conclusions regarding the reasons standing behind achieved results. There is just not enough data gathered. The question: stream or not to stream seems to have following answers.
🌐
Scaledcode
blog.scaledcode.com › blog › java-streams-performance
Performance Differences of Java Streams - Scaled Code
July 18, 2022 - From our tests it looked like the flip from the double stream to the group by being more efficient happens somewhere between 1,000 and 50,000 items. Knowing that our result set would always be less than or equal to 25 we not only decided that the readability was better but we had given ourselves confidence that our original solution was more performant than the group by anyway. Finding this interesting we decided to dig a little further to see if previous or newer versions of Java would have different results.
🌐
Javapro
javapro.io › home page › java streams evolution: from java 8 to today
Java Streams Evolution: Key Features from Java 8 to today
November 13, 2025 - The JVM can now distribute work more efficiently across multiple threads, reducing overhead during the processing of large data sets. As a result, applications can handle larger collections with improved performance ...
🌐
Reddit
reddit.com › r/learnjava › java stream drastically increases execution time compared to for loop
r/learnjava on Reddit: Java Stream drastically increases execution time compared to for loop
November 3, 2024 -

I was solving a LeetCode problem where I needed to sum the elements of an array. At first, I used a stream to get the sum, and the runtime was 7 ms, which was faster than roughly 18% of other users' solutions. When I replaced the stream with a for loop, the runtime improved to 3 ms, beating a little bit over 85% of other users' submitted solutions

Replaced this:

Arrays.stream(arr).reduce((a,b)-> a+b).orElse(0)

With this code:

for(int x=0; x<arr.length; x++) {

total += x;

}

I tested different scenarios on my local machine and stream was always slower. The difference in runtime is huge and drastically increases as you increase your data size.

I always thought stream was better than enhanced for loop, a while loop and other iteration construct. When is stream preferred over traditional looping methods?

Top answer
1 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 4
1
When you don't care about performance, obviously. Java streams have the parallelization feature, but this is not something you should enable by default. You'll have to measure this on your workload.
🌐
Daniellas
daniellas.tech › posts › speed-of-stream.html
Speed of stream. Nice but slow abstraction? Myths debunked.
Functional Programming, Java, JavaScript, Software Architecture, Software Craftsmanship, Clean Code
🌐
DZone
dzone.com › data engineering › data › java 8 stream performance benchmarks
Java 8 Stream Performance Benchmarks
September 11, 2015 - first thing i noticed: my laptop performs much better than the machine used for the jax article. this was to be expected as it was described as “outdated hardware (dual core, no dynamic overclocking)” but it made me happy nevertheless since i paid enough for the damn thing. instead of 0.36 ms it only took 0.130 ms to loop through the array. more interesting are the results for using a stream to find the maximum:
🌐
Devmio
devm.io › java › java-performance-tutorial-how-fast-are-the-java-8-streams-118830
Java performance tutorial – How fast are the Java 8 streams?
July 27, 2015 - In this JAX Magazine sneak preview, JAX London speaker Angelika Langer answers the most important question for anyone using Java streams: are they really faster?
🌐
DEV Community
dev.to › haraf › java-streams-balancing-performance-and-thread-safety-like-a-pro-42od
🔄 Java Streams: Balancing Performance and Thread Safety Like a Pro - DEV Community
April 23, 2025 - ✅ Use streams for readable, declarative code ⛔ Avoid in tight performance-sensitive loops 🧵 Never share mutable state across threads 📦 Prefer immutable data and thread-safe collectors ⚙️ Profile before going parallel · Java Streams are a modern toolkit for expressive data manipulation, but they’re not magic.
🌐
InfoQ
infoq.com › articles › java-collections-streams
How to Speed up Large Collections Processing in Java - InfoQ
August 26, 2022 - While Streams simplified dealing with large collections and coding operations on large collections, it was not always a guarantee of improved performance; indeed, programmers frequently found that using Streams actually slowed processing.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › Stream.html
Stream (Java Platform SE 8 )
2 weeks ago - If consistency with encounter order is required, and you are experiencing poor performance or memory utilization with distinct() in parallel pipelines, switching to sequential execution with BaseStream.sequential() may improve performance. Returns: the new stream · Stream<T> sorted() Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
🌐
nipafx
nipafx.dev › java-stream-performance
Stream Performance - nipafx.dev
September 7, 2015 - A close look at stream performance. How do they compare to for and for-each loops oder arrays and lists. And what roles play boxing and the complexity of the executed operation? ... Want to play around with the code yourself? Check out the repository Benchmark Lab, a collection of various JMH-based Java benchmarks - it contains many of the snippets shown in this blog post.
🌐
Baeldung
baeldung.com › home › java › java streams › streams vs. loops in java
Streams vs. Loops in Java | Baeldung
January 8, 2024 - Let’s walk through a comprehensive benchmarking example to understand the performance differences between for-loops and streams. We’ll compare the execution times of complex operations involving filtering, mapping, and summing using both for-loops and streams. For this purpose, we’ll use the Java Microbenchmarking Harness (JMH), a tool designed specifically for benchmarking Java code.