We verified the processing speed of Stream or extended for statement when operating on ** elements of a specific type ** contained in arrays and collections.
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.
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