"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Are Streams Always Slower Than Traditional Collections for Simple Operations?

Are Streams Always Slower Than Traditional Collections for Simple Operations?

Published on 2024-11-08
Browse:185

Are Streams Always Slower Than Traditional Collections for Simple Operations?

Java 8 Stream Performance Vs. Traditional Collections

You've recently ventured into Java 8 and conducted an informal benchmark to compare the performance of its Stream API against classic Collections. Your test involves filtering a list of integers, extracting the square root of even numbers, and storing the results in a Double list. However, you're questioning the validity of your test and are eager to clarify the true performance implications.

Assessing the Benchmark Test

Your initial results, which indicated streams to be slower than collections, raised concerns. To ensure a more reliable evaluation, it's essential to address potential errors and conduct a fair test. Here are some considerations:

  • Using LinkedList: LinkedList is not an optimal choice for the result list as it lacks efficient random access. Consider using ArrayList instead.
  • Benchmark Methodology: Manual benchmarking can be prone to inaccuracies. Utilize a benchmarking framework like JMH (Java Microbenchmarking Harness) to provide more precise and reliable measurements.

Proper Benchmarking Results

Following these recommendations, let's revisit the performance evaluation using JMH and improved benchmarking strategies:

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

    static List sourceList = new ArrayList();
    static {
        for (int i = 0; i  vanilla() {
        List 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 stream() {
        return sourceList.stream()
                .filter(i -> i % 2 == 0)
                .map(Math::sqrt)
                .collect(Collectors.toCollection(
                    () -> new ArrayList(sourceList.size() / 2   1)));
    }
}

Results:

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

Findings

Contrary to the initial results, the JMH benchmark clearly shows that the traditional collection approach is significantly faster than the stream approach in this particular scenario.

Conclusion

Based on these improved benchmarking results, we can conclude that:

  • Streams are not inherently slower than collections. However, their overhead can outweigh the benefits in certain use cases, such as simple filtering and mapping operations.
  • Streams offer significant advantages in terms of code simplicity and maintainability. They simplify data processing pipelines and reduce boilerplate code.
  • For performance-critical code paths, it's always advisable to conduct thorough benchmarking and consider the specific requirements of your application.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3