[JAVA] Comparison of processing speed between Stream including cast and extended for statement

Introduction

We verified the processing speed of Stream or extended for statement when operating on ** elements of a specific type ** contained in arrays and collections.

Code to prepare in advance

Array of 100 million elements


Object[] objects = new Object[100_000_000];
for (int i = 0; i < 50_000_000; i++)
    objects[i] = new Object();
for (int i = 50_000_000; i < 100_000_000; i++)
    objects[i] = "";

ArrayList with 100 million elements


List<Object> objects = new ArrayList<>();
for (int i = 0; i < 50_000_000; i++)
    objects.add(new Object());
for (int i = 0; i < 50_000_000; i++)
    objects.add("");

This time we will verify using an array and ArrayList. It stores 50 million Object type and 50 million String type elements.

Verification

Stream


long start = System.currentTimeMillis();
objects.stream() // Arrays.stream(objects)
    .filter(String.class::isInstance)
    .map(String.class::cast)
    .forEach(String::toUpperCase);
long finish = System.currentTimeMillis();
System.out.println(finish - start + "ms");
type time
Array 345ms
ArrayList 409ms

The array seems to be a little faster.

Extended for statement


long start = System.currentTimeMillis();
for (Object obj : objects) {
    if (obj instanceof String) {
        ((String) obj).toUpperCase();
    }
}
long finish = System.currentTimeMillis();
System.out.println(finish - start + "ms");
type time
Array 122ms
ArrayList 212ms

In this comparison, we found that the extended for statement is faster than the Stream [^ 1]. Since I don't usually write code that handles millions or ten millions of elements, I often use streams without being conscious of it, but it seems that streams need to be used with caution when focusing on performance.

[^ 1]: We apologize for any inconvenience in the measurement method, but we would appreciate it if you could let us know.

Recommended Posts

Comparison of processing speed between Stream including cast and extended for statement
Compare the speed of the for statement and the extended for statement.
[Java] for statement / extended for statement
About merge processing implementation including sorting function of Stream API
[Java] Make variables in extended for statement and for Each statement immutable
Comparison of Web App for Containers and Azure Container Instances
About for statement and if statement
Utilization of Java array elements, for, length, value, and extended for statements
Comparison of processing times based on awk, shell command, and Java