I think I'm doing it somewhere, but I'm going to try the performance when using Stream with Java 8.
■Java
java
$ java -version
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
■Eclisep
Version: Neon.1a Release (4.6.1)
argument
--List of String
things to do
--Sort the list --Loop the list and concatenate with StringBuilder --Exclude if the list string starts with a specific character
public void sortList(List<String> list) {
StringBuilder sb = new StringBuilder();
Collections.sort(list);
for (String str : list) {
if (!str.startsWith("Pe")) {
sb.append(str);
}
}
}
public void sortList(List<String> list) {
StringBuilder sb = new StringBuilder();
list.stream()
.filter(str -> !str.startsWith("Pe"))
.sorted()
.forEach(str -> sb.append(str));
}
Executes the process of looping the test method 1 million times 10 times.
public static void main(String[] args) {
//List to use in test method arguments
List<String> list = Arrays.asList(
"Yute"
,"Miyaou"
,"Kimuko"
,"1234567"
,"abcdefg"
,"Pepe Pepe"
);
//Let's write a test execution loop with Stream
IntStream.rangeClosed(1, 10).forEach(i -> {
long start = System.currentTimeMillis();
StreamTest test = new StreamTest();
IntStream.rangeClosed(1, 1000000).forEach(j -> {
test.sortList(list);
});
System.out.println("[time]" + (System.currentTimeMillis() - start) + "(msec)");
});
}
[time]174(msec)
[time]144(msec)
[time]161(msec)
[time]117(msec)
[time]136(msec)
[time]204(msec)
[time]132(msec)
[time]133(msec)
[time]126(msec)
[time]127(msec)
[time]526(msec)
[time]442(msec)
[time]684(msec)
[time]373(msec)
[time]378(msec)
[time]335(msec)
[time]363(msec)
[time]364(msec)
[time]390(msec)
[time]353(msec)
In the code I tried this time, it took twice to more than twice as long when using Stream.
However, since it is a large number of loops with simple processing, it seems that this result was obtained. (I feel that the same result will not be obtained when it is put into practical use.)
Also, since this is the first implementation of Stream, it may not be possible to implement using Stream.
Regarding readability, in the case of this test, I think that those who are accustomed to the code so far will obviously find it easier to see using the for
statement,
Once I got used to it, the syntax using Stream was obvious, and I felt that it was easy to understand.
By the way, the following code made it a little faster.
public void sortListAsStream(List<String> list) {
StringBuilder sb = new StringBuilder();
list.stream()
.sorted()
.forEach(str -> {
if (!str.startsWith("Pe")) {
sb.append(str);
}
});
}
[time]456(msec)
[time]409(msec)
[time]328(msec)
[time]552(msec)
[time]316(msec)
[time]257(msec)
[time]272(msec)
[time]289(msec)
[time]305(msec)
[time]306(msec)
Recommended Posts