How optimized are Java 8 stream filters by collection methods?

For example, I have a comma delimited string:

String multiWordString= "... , ... , ... ";

And I want to check if another str line is present in the csv line. Then I can do the following two things:

1.

boolean contains = Arrays.asList(multiWordString.split(",")).contains(str);

2.

boolean contains = Arrays.asList(multiWordString.split(",")).stream().filter(e -> e.equals(str)).findFirst();

EDIT: The example line uses a comma as a separator. I had to use a better name for the example string to avoid confusion. I updated the name. In this question, I'm trying to find a performance difference between using Java 8 threads and loop / collection methods.

+4
source share
3 answers

, , , . , - ...

( ):

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
public class CSVParsing {
    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder().include(CSVParsing.class.getSimpleName())
                .jvmArgs("-ea")
                .shouldFailOnError(true)
                .build();
        new Runner(opt).run();
    }

    @Param(value = { "a,e, b,c,d",
            "a,b,c,d, a,b,c,da,b,c,da,b,c,da,b,c,da,b,c,da,b,c,da,b,c,da,b,c,d, e",
            "r, m, n, t,r, m, n, tr, m, n, tr, m, n, tr, m, n, tr, m, n, tr, m, n, tr, m, n, t, e" })
    String csv;

    @Fork(1)
    @Benchmark
    public boolean containsSimple() {
        return Arrays.asList(csv.split(",")).contains("e");
    }

    @Fork(1)
    @Benchmark
    public boolean containsStream() {
        return Arrays.asList(csv.split(",")).stream().filter(e -> e.equals("e")).findFirst().isPresent();
    }

    @Fork(1)
    @Benchmark
    public boolean containsStreamParallel() {
        return Arrays.asList(csv.split(",")).stream().filter(e -> e.equals("e")).findFirst().isPresent();
    }
}

, , :

 CSVParsing.containsSimple   (first Parameter)    181.201 ±   5.390
 CSVParsing.containsStream                        255.851 ±   5.598
 CSVParsing.containsStreamParallel                295.296 ±  57.800

( ), .

: 100 ; : nano-seconds.

, ; , csv, , .

+6

"" : .

2 . , 2 1. !

. csv , ( , - csv. csv (, , ), .

+2

, CSVs, , , , , theres , . , , CSV.

, , Arrays.stream Stream.of()

, , .

.contains(str) , .

, .

, , , , , , .

+2

Source: https://habr.com/ru/post/1678304/


All Articles